0ms JAVA simple solution


  • 4
    V

    public class Solution {

    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return root;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        
        invertTree(root.left);
        invertTree(root.right);
        
        return root;
    }
    

    }


  • 4
    J

    You can simplify this even more with the following:

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

  • 0
    M

    Could you please tell me what the difference between this two answers,because my submission is also like that


  • 0
    Z

    But the previous is easier to understand. Clearly, pre order tree traversal shall be applied.


  • 0

    Just one question. If the original tree is not sorted and we need to compare the value of left and right before exchanging.How should we code?I add "if (root.left.val<root.right.val)" but it turns out a run time error on that line.


  • 0
    M

    yeh, i also think so, but i don not understand the above answer, how to get that?


  • 0
    J

    @mingfang2 they're both exactly the same except mine uses less variables


  • 0
    M

    @jjung ok thx


Log in to reply
 

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