Invert a binary tree.
First of all, consider recursive solution.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root = null)
return null;
TreeNode lft = root.left;
root.left = invertTree(root.right);
root.right = invertTree(root.lft);
return root;
}
}
Also, we can use queue to do BFS.
public TreeNode invertTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if(root = null) return null;
queue.offer(root);
while(!queue.isEmpty()){
TreeNode now = queue.poll();
TreeNode left = now.left;
now.left = now.right;
now.right = left;
if(node.left != null){
queue.offer(now.left);
}
if(node.left != null){
queue.offer(now.right);
}
}
return root;
}