zoukankan      html  css  js  c++  java
  • 树5:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

    分析:层次遍历的经典算法

    import java.util.ArrayList;
    import java.util.*;
    
    /*
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    
    }
    */
    public class Solution {
        ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
            ArrayList<ArrayList<Integer> >list=new ArrayList<ArrayList<Integer> >();
            if(pRoot==null) return list;
            int layer=1;
            Queue<TreeNode>q=new LinkedList<>();
            q.offer(pRoot);
            while(!q.isEmpty()){
                int count=q.size();
                ArrayList<Integer> temp=new ArrayList<>();
                while(count>0){
                    TreeNode node=q.poll();
                    temp.add(node.val);
                    if(node.left!=null) q.offer(node.left);
                    if(node.right!=null) q.offer(node.right);
                    count--;
                }
                layer++;
                list.add(temp);
            }
            return list;
        }
        
    }
  • 相关阅读:
    web 移动端 适配
    meta
    meta设置
    时间
    CentOS下配置nginx conf/koi-win为同一文件的各类错误
    CentOS7 配置LAMP
    centos 进度条卡死
    LeetCode02:两数相加
    LeetCode01:两数之和
    单链表类,链表逆置
  • 原文地址:https://www.cnblogs.com/xuechengmeigui/p/12638210.html
Copyright © 2011-2022 走看看