二叉树的层次遍历

1.LEETCODE102 
二叉树的层次遍历 
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 
解题思路: 
1.逐层添加到队列

例如: 
给定二叉树: [3,9,20,null,null,15,7],


/ \ 
9 20 
/ \ 
15 7 
返回其层次遍历结果:


[3], 
[9,20], 
[15,7] 
]

class Solution {
    //层次遍历采用队列实现
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if(root == null)
            return list;
        //层次遍历
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(true){
            Queue<TreeNode> temp = new LinkedList<>();
            List<Integer> tempList = new ArrayList<>();
            while(!queue.isEmpty()){
                TreeNode t = queue.poll();
                tempList.add(t.val);
                if(t.left!=null)
                    temp.add(t.left);
                if(t.right!=null)
                    temp.add(t.right);
            }
            list.add(tempList);//自顶向下输出
            if(temp.isEmpty())
                break;
            queue = temp;
        }
        return list;
    }
}

2.LEETCODE107 
二叉树的层次遍历 II 
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如: 
给定二叉树 [3,9,20,null,null,15,7],


/ \ 
9 20 
/ \ 
15 7 
返回其自底向上的层次遍历为:


[15,7], 
[9,20], 
[3] 
]

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
         List<List<Integer>> list = new ArrayList<>();
        if(root == null)
            return list;
        //层次遍历
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(true){
            Queue<TreeNode> temp = new LinkedList<>();
            List<Integer> tempList = new ArrayList<>();
            while(!queue.isEmpty()){
                TreeNode t = queue.poll();
                tempList.add(t.val);
                if(t.left!=null)
                    temp.add(t.left);
                if(t.right!=null)
                    temp.add(t.right);
            }
            list.add(0,tempList);//自底向上输出
            if(temp.isEmpty())
                break;
            queue = temp;
        }
        return list;
    }
}
--------------------- 
作者:长弓Smile 
来源:CSDN 
原文:https://blog.csdn.net/u012485480/article/details/80762275 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值