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
    }
  • 相关阅读:
    forEach与迭代器
    JavaMap
    java stack
    Java的Iterator迭代器
    JavaScript基础知识汇总
    Http协议总结
    以太坊交易剔重规则
    localhost与127.0.0.1与0.0.0.0
    boost之asio
    调和级数求和
  • 原文地址:https://www.cnblogs.com/mlebk/p/12632506.html
Copyright © 2011-2022 走看看