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;
}
}
Easy iterative in java


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; }
