• 二叉树的层序遍历


    从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。..广度优先遍历的修改版。

    /*

    public class TreeNode {

        int val = 0;

        TreeNode left = null;

        TreeNode right = null;

     

        public TreeNode(int val) {

            this.val = val;

     

        }

     

    }

    */

    /**这里是广度优先遍历的变体。广度优先遍历不要求每一层输出一行。需要使用队列作为辅助

    这里需要在过程中得到每一层的节点个数就可以了,用start和end标志表示,end表示每层节点的个数,start标志此层输出了多少个了。

    */

    public class Solution {

        ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {

            ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();

                 if(pRoot==null)

                return result;

            Queue<TreeNode> q=new LinkedList<TreeNode>();

            ArrayList<Integer> list=new ArrayList<Integer>();

            q.add(pRoot);

            int start=0,end=1;

            while(!q.isEmpty()){

             TreeNode node=q.remove();

                list.add(node.val);

                start++;//输出一个start就加一

                if(node.left!=null)

                    q.add(node.left);

                if(node.right!=null){

                    q.add(node.right);

                }

                if(start==end){//当输出个数与这一层的节点数相同时,表示这一层输出结束

                    start=0;

                    end=q.size();

                    result.add(list);

                    list=new ArrayList<Integer>();

                   

                }

              

              

            }

           

           

            return result;

        }

       

    }

    也可以不使用start和end,上面的while换成下面形式。for循环用以输出当前层的所有节点,一个for循环表示一层

     while(!q.isEmpty()){

                int size=q.size();

                for(int i=0;i<size;i++){

                    TreeNode node=q.poll();

                    list.add(node.val);

                    if(node.left!=null)

                         q.add(node.left);

                         if(node.right!=null){

                             q.add(node.right);

                            }

                   

                }

                result.add(list);//将每层的输出加到总的输出中

                list=new ArrayList<>();

    }

     

  • 相关阅读:
    对话框风格的窗口
    对话框
    Notification的功能与用法
    滚动视图(ScrollView)的功能与用法
    css----overflow(布局)
    css----display(显示) 与 Visibility(可见性)
    css----position(定位)
    Vue.js----router(路由)
    HTTP协议-Cookie和Session详解
    MySql 复制表命令
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8024720.html
Copyright © 2020-2023  润新知