题目简介
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.
自己的解法
- public class Solution {
public TreeNode invertTree(TreeNode root) {
TreeNode temp;
if(root==null)
return root;
else{
temp=root.right;
root.right=invertTree(root.left);
root.left=invertTree(temp);
return root;
}
}
}
这道题目的意思就是实现二叉树的左右子树的互换。读完题目,马上就想到了用递归的方法。递归最重要的两个思想就是
1.确定好递归的出口
2.递归的调用自身
这道题的出口很简单,但是递归的调用自身需要我们稍微加点变换。这个函数的返回值一个二叉树的节点类型那么最后的答案肯定是左右子数均交换完毕的二叉树的根。那么我们在递归调用自身时,不能直接return invertTree(root.left);最后返回的肯定还是根。这里需要我们先定义一个节点保存左子树(不保存的话如果对右子树执行该函数赋值给左子树,那么原本的左子树就会丢失),分别对左右子树调用这个函数。然后再将左右子树调换即可,最后返回root。
Hot解法
看了一下Hot解法的递归实现基本上和我的算法大同小异。这里介绍一下非递归的算法,用栈或者队列都可以实现。
- 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;
}
}