My recursive Java solution. That was easy.


  • 0
    Q
    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            invert(root);
            return root;
        }
        private void invert(TreeNode n){
            if (n == null){
                return;
            }
            TreeNode temp = n.left;
            n.left = n.right;
            n.right = temp;
            invert(n.left);
            invert(n.right);
        }
    }

  • 0
    T

    why this is WA

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

  • 0
    Q

    Look at code above to figure out what's missing.


  • 0
    Z

    You should learn more about the pointer. You create pointers left and right pointing to n.left and n.right. Then you use swap method to let pointer left point to n.right and pointer right point to n.left. But you do nothing about the tree. You just let pointers that you create change the aims they point, but the tree has no change. Maybe you can understand.


Log in to reply
 

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