Given the root
of a binary tree, invert the tree, and return its root.
Eg:
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Solution one:
Recursion:
class Solution {
public TreeNode invertTree(TreeNode root) {
return invertTreeHelper(root);
}
if(root == null) return null;
TreeNode left = invertTreeHelper(root.left);
TreeNode right = invertTreeHelper(root.right);
TreeNode temp = left;
root.left = right;
root.right = temp;
return root;
}
}
Iterative:
class Solution {
public TreeNode invertTree(TreeNode root) {
return invertTreeHelper(root);
}
public TreeNode invertTreeHelper(TreeNode root){
if(root == null) return null;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty() ){
TreeNode current = queue.poll();
TreeNode temp = current.left;
current.left = current.right;
current.right = temp;
if(current.left != null) queue.add(current.left);
if(current.right != null) queue.add(current.right);
}
return root;
}
}
Hints:
1: Understand Recursion
2: Know the logic of Iterative, If current treenode is not null, queue.add(TreeNode)
3: LinkedList implement the interface of queue