8 line java solution easy to understand


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

  • 0
    L

    I had the same idea. But I would do a bit differently.

    Since you check the incoming parameter (root != null), it is not completely necessary to check the root.left != null and root.right != null.

    Although it would cost another two recursive invocations for each leaf node, we save two boolean checks for each invocation of the function.


Log in to reply
 

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