Skip to content
The Chat Archive
vicuna-33b· LMSYS Arena Human Preference 55K

write a java method to invert a binary tree

  1. User

    write a java method to invert a binary tree

  2. Assistant

    In order to invert a binary tree, you need to recursively traverse and swap the nodes. Here's a method that does this:

    public class BinaryTreeNode {
        public int value;
        public BinaryTreeNode left;
        public BinaryTreeNode right;
    
        public BinaryTreeNode(int value) {
            this.value = value;
            this.left = this.right = null;
        }
    }
    
    public class BinaryTree {
        public BinaryTreeNode root;
    
        public BinaryTree() {
            this.root = null;
        }
    
        public void invertTree() {
            if (root == null) {
                return;
            }
    
            BinaryTreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
    
            invertTreeRecursive(root.left);
            invertTreeRecursive(root.right);
        }
    
        private void invertTreeRecursive(BinaryTreeNode node) {
            if (node == null) {
                return;
            }
    
            BinaryTreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
    
            invertTreeRecursive(node.left);
            invertTreeRecursive(node.right);
        }
    }
    

    This code first inverts the nodes directly, and then recursively inverts the left and right subtrees.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.