Trees

Invert a Binary Tree

Estimated reading: 1 minute 43 views

Solution 1

				
					public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        
        TreeNode node = new TreeNode(root.val);

        node.right = invertTree(root.left);
        node.left = invertTree(root.right);
        
        return node;
    }
				
			

Solution 2

				
					class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        // Base case: if the tree is empty or we reach a leaf node, return null
        if (root == null) {
            return null;
        }

        // Recursively invert the left and right subtrees
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);

        // Swap the left and right children
        root.left = right;
        root.right = left;

        // Return the root (now with inverted children)
        return root;
    }
}

				
			
Share this Doc

Invert a Binary Tree

Or copy link

CONTENTS