Java simple recursive solution


  • 0
    M

    Simply recurse left and right and then swap the leaves nodes.

    68 / 68 test cases passed.
    Runtime: 0 ms

    public class Solution {
        
        public TreeNode invertTree(TreeNode root) {
            root = invert(root);        
            return root;
        }
        
        private TreeNode invert(TreeNode root) {
            if (root == null) return null;
            invert(root.left);
            invert(root.right);
            TreeNode left = root.left;
            TreeNode right = root.right;
            root.left = right;
            root.right = left;
            return root;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.