0
点赞
收藏
分享

微信扫一扫

超详细从上到下打印二叉树JS语言

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回:

[3,9,20,15,7]

分析:这就是一个在数据结构中为广度优先遍历的方法,先从跟节点开始,在从根节点的子节点开始,在分别取根节点的子节点.......以此循环遍历。

就实例而言:我创建了两个数组:queue为临时数组。res为最终数组。

先将3放入最终数组中,再将子节点9,20放在临时数组中。此时9为临时数组中根节点。

则将9放在最终数组中,再将子节点null,null放到临时数组中(为空)。此时20为临时数组中根节点。

则将20放在最终数组中,再将子节点15,7放在临时数组中。此时15为临时数组根节点

......................................................................以此循环。

实现代码

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var levelOrder = function(root) {
       if(!root){
         return []
       }
   
         let queue = [];let res = []
       queue.push(root)
       while(queue.length!=0){
           node = queue.shift()
           res.push(node.val)
           if(node.left){
               queue.push(node.left)
           }
           if(node.right){
               queue.push(node.right)
           } 

       }
              return res;
      
};

shift是取数组最走前面的元素(删掉数组最前边元素,并返回该元素的值) 

举报

相关推荐

0 条评论