226.Invert Binary Tree
Solution 1:DFS, Recursion On
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
else{
TreeNode newLeft = invertTree(root.right);
TreeNode newRight = invertTree(root.left);
root.left = newLeft;
root.right = newRight;
return root;
}
}
}
Solution 2 BFS On
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
Queue<TreeNode> queue = new LinkedList<>();
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;
}
}