Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
This problem was inspired by this original tweet by Max Howell :
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//递归解法
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
//迭代解法
//思路就是利用一个容器作为缓冲,每次从容器中取出一个node,交换它的left与right,再将子节点放入容器
//关键是要保证每个node的left与right都能被交换,而至于容器用queue还是stack都是无所谓的,只要保证容器
//内的node顺序不乱就行
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode curNode = queue.remove(); //返回并移除队头
TreeNode temp = curNode.left;
curNode.left = curNode.right;
curNode.right = temp; //交换队头的left与right
if(curNode.left != null){ //再把left与right均入队
queue.add(curNode.left);
}
if(curNode.right != null){ //此处两个入队的顺序是无关紧要的
queue.add(curNode.right); //主要就是每次从队中取出一个node,交换它的left与right
} //然后在把他的子节点也入队,实现类似递归的过程
}
return root;
}
}
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode curNode = stack.pop();
TreeNode temp = curNode.left;
curNode.left = curNode.right;
curNode.right = temp;
if(curNode.left != null){
stack.push(curNode.left);
}
if(curNode.right != null){
stack.push(curNode.right);
}
}
return root;
}
}