题目描述(简单难度)
反转二叉树,将二叉树所有的节点的左右两个孩子交换。
解法一 递归
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
val=x;
}
}
public class Invert_Binary_Tree {
public static TreeNode invertTree(TreeNode root){
if(root==null) return root;
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
解法二 DFS 栈
当然递归都可以用栈模拟,因为解法一的递归比较简单,所以改写也比较容易。
public class Invert_Binary_Tree2 {
public TreeNode invertTree(TreeNode root){
Stack<TreeNode>stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
if(cur==null) continue;;
TreeNode temp = cur.left;
cur.left=cur.right;
cur.right=temp;
stack.push(cur.right);
stack.push(cur.left);
}
return root;
}
}
解法三 BFS队列
既然可以DFS,那么也可以BFS,只需要讲解法二的栈改为队列即可。代码不用怎么变,但二叉树的遍历顺序完全改变了。
import java.util.LinkedList;
import java.util.Queue;
public class Invert_Binary_Tree3 {
public TreeNode invertTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur == null) continue;
TreeNode temp = cur.left;
cur.left = cur.right;
cur.right = temp;
queue.offer(cur.left);
queue.offer(cur.right);
}
return root;
}
}
总结
DFS一般和栈关联在一起,BFS一般和队列关联在一起。之前一直认为,递归改写成解法二或者解法三的迭代那样会更好一些,因为可以防止递归的堆栈溢出。虽然也有缺点,那就是代码会相对更复杂些,可读性有些降低。
看到王垠的观点,分享一下:
参考文献
- https://zhuanlan.zhihu.com/p/106837631