226. Invert Binary Tree

题目描述(简单难度)

在这里插入图片描述
反转二叉树,将二叉树所有的节点的左右两个孩子交换。

解法一 递归
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安替-AnTi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值