Straightforward Java recursive DFS solution


  • 8
    T
    public TreeNode invertTree(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) return root;
        
        TreeNode left = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(left);
        return root;
    }

  • 0
    W

    Do we still need to check that left == null && right == null?


  • 0

    this will work but in the case that only 1 of the left or right is null you'll pass the if check and end up checking null again on recursion. Not a big deal but may as well clean it up a little as follows (C#)

        public TreeNode InvertTree(TreeNode root) 
        {
            if (root != null)
            {
                TreeNode leftInverted = InvertTree(root.left);
                TreeNode rightInverted = InvertTree(root.right);
                root.left = rightInverted;
                root.right = leftInverted;
            }
            return root;
        }
    

Log in to reply
 

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