Easy iterative in java


  • 8
    C
    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null) return root;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            while(!queue.isEmpty()){
                TreeNode node = queue.poll();
                TreeNode tmp = node.left;
                node.left = node.right;
                node.right = tmp;
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
            return root;
        }
    }

  • 7
    M

    I think this way is much easier. Invert tree from bottom to up recursion.

       public TreeNode invertTree(TreeNode root) {
    	if(root==null) return root; // Note: never forget root may be null!
    	if(root.left==null && root.right==null) return root;
    	
    	TreeNode temp = invertTree(root.left);
        root.left = invertTree(root.right);
        root.right = temp;
        
    	return root;
    }
    

  • 0
    C

    Great solution! I just like solving problems in a different way. Cheer!!


  • 0
    R

    Indeed it's easier, but better not use recursion if you can think of another way because recursion depletes the system stack quickly


  • 0
    L

    Thank you point it out. For recursion method, there is also a concern on concurrency, I don't understand this very well, maybe it is because two threads accessing the same variable? Can you explain or provide some links for me?


  • 0
    H

    @MadDetective No need to check

    if(root.left==null && root.right==null) return root;
    

Log in to reply
 

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