zoukankan      html  css  js  c++  java
  • 树---把二叉树打印成多行

    从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

    分析:首先先把根节点放入要打印的队列中,在打印之前把其子节点保存在队列中,

    这里需要有一个list存放当前层的节点,有个计数器记还有多少节点要打印,下一层由多少节点。

    /* function TreeNode(x) {
        this.val = x;
        this.left = null;
        this.right = null;
    } */
    function Print(pRoot)
    {
        // write code here
        const queue=[],res=[]
        if(pRoot===null){
            return res
        }
        queue.push(pRoot)
        let nextLevel=0//下一层节点的个数
        let toBePrinted=1//这一层还有多少节点要打印
        let list=[]//存放每一层的节点
        while(queue.length){
            const pNode=queue.shift()
            list.push(pNode.val)
            if(pNode.left!==null){
                queue.push(pNode.left)
                nextLevel++
            }
            if(pNode.right!==null){
                queue.push(pNode.right)
                nextLevel++
            }
            toBePrinted--
            if(toBePrinted==0){
                res.push(list)
                list=[]
                toBePrinted=nextLevel
                nextLevel=0
            }
        }
        return res
    }
  • 相关阅读:
    调用google地图
    jQuery放大镜效果
    jQuery拖到效果
    jQuery制作相册
    jQuery ui插件用法
    jQuery写fadeTo方法
    jQuery实现动画效果
    jQuery的slideToggle方法
    控经纬度显示地图与卫星
    像百度那样的智能感知效果
  • 原文地址:https://www.cnblogs.com/mlebk/p/12632506.html
Copyright © 2011-2022 走看看