代码随想录二叉树(2)

层序遍历

对应图论里面的广度优先算法。

ArrayDeque和LinkedList用作队列的区别

https://cloud.tencent.com/developer/article/2348751

自己写出来了,不过比较长,while循环可以优化一下,大循环里放isEmpty();

public List<List<Integer>> levelOrder(TreeNode root) {
        List result = new ArrayList();
        List<Integer> list = new ArrayList();
        //构建队列
        Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
        if(root == null){
            return result;
        }
        TreeNode cur = new TreeNode();
        TreeNode temp = new TreeNode();
        List temp_list = new ArrayList();
        cur = root;
        queue.offer(cur);
        int size = queue.size(); 
        while(size != 0){
            temp = queue.poll();
            list.add(temp.val);
            if(temp.left != null){
                queue.offer(temp.left);
            }
            if(temp.right != null){
                queue.offer(temp.right);
            }
            size --;
            if(size == 0 && (!queue.isEmpty())){
                size = queue.size();
                temp_list = list;
                result.add(temp_list);
                list = new ArrayList();
            }
        }
        result.add(list);
        return result;

在这里插入图片描述

反转二叉树

用前序或者后序遍历比较简单
自己写的时候犯了个错误:用前序遍历的时候里面还加了for循环,其实递归方法里,if(root==null)其实就有控制递归的终止条件
在这里插入图片描述

有三种方法,这次主要掌握递归法:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值