剑指 Offer | DPS,BFS

32 - I. 从上到下打印二叉树 | BFS

class Solution {
   
    public int[] levelOrder(TreeNode root) {
   
        if(root==null){
   
            return new int[0];
        }
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> q = new LinkedList<>();
        q.add(root);
        while(!q.isEmpty()){
   
            TreeNode tmp = q.poll();
            res.add(tmp.val);
            if(tmp.left!=null)
              q.add(tmp.left);
            if(tmp.right!=null)
                q.add(tmp.right);
        }
        int[] ans = new int[res.size()];
        for(int i=0;i<res.size();i++)
            ans[i]=res.get(i);
        return ans;
    }
}

32 - II 从上到下打印二叉树 II | 层序遍历

思路一:在每一层将元素add到queue中,统计下一层元素个数到tmp中。

class Solution {
   
    public List<List<Integer>> levelOrder(TreeNode root) {
   
        if(root==null) return new LinkedList<>();
        Queue<TreeNode> q = new LinkedList<>(); //用来存储要遍历的点
        List<List<Integer>> res = new LinkedList<>();
        q.add(root);
        int num = 1; //统计当前层元素的个数
        while(!q.isEmpty()){
   
            int tmpNum = 0;
            List<Integer> tmp =new LinkedList<>();
            for(int i=0;i<num;i++){
   
                TreeNode tmpNode = q.poll();
                tmp.add(tmpNode.val);
                if(tmpNode.left!=null){
   
                    q.add(tmpNode.left);
                    tmpNum+=1;
                }
                if(tmpNode.right!=null){
   
                    q.add(tmpNode.right);
                    tmpNum+=1;
                }
            }
            res.add(tmp);
            num = tmpNum;
        }
        return res;
    }
}

🌟 思路二:下一层要遍历的次数就是上一层加完结束之后队列的长度。

class Solution {
   
    public List<List<Integer>> levelOrder(TreeNode root) {
   
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        if(root != null) queue.add(root);
        while(!queue.isEmpty()) {
   
            List<Integer> tmp = new ArrayList<>();
            for(int i = queue.size(); i > 0; i--
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值