Do not understand why my solution doesn't work. Any help?


  • 0
    S

    My solution

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

    The solution provided is like

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

    The only thing differs between my code and the solution is that I did not create two TreeNode variables and directly assign the result to root.left and root.right. Any thought?


  • 1
    C
    root.left = invertTree( root.right );
    

    root.left value is changed after this line....


  • 0
    S

    Oh, never notice that. Thanks.


Log in to reply
 

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