102、二叉树的层序遍历 | JS

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

 

示例:
二叉树:[3,9,20,null,null,15,7],

3
/
9 20
/
15 7
返回其层序遍历结果:

[
[3],
[9,20],
[15,7]
]

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val, left, right) {
 4  *     this.val = (val===undefined ? 0 : val)
 5  *     this.left = (left===undefined ? null : left)
 6  *     this.right = (right===undefined ? null : right)
 7  * }
 8  */
 9 /**
10  * @param {TreeNode} root
11  * @return {number[][]}
12  */
13 var levelOrder = function(root) {
14     if(!root) return[];
15     const q = [[root,0]];  //把队列的每一项改成数组,用来保存层级
16     const res = []; //保存结果
17     while(q.length){    //利用队列
18         const [n,level] = q.shift();
19         if(!res[level]) {
20             res.push([n.val]);
21         } else {
22             res[level].push(n.val);
23         }
24      //   console.log(n.val, level);
25         if(n.left) q.push([n.left,level+1]);
26         if(n.right) q.push([n.right,level+1]);
27     }
28     return res;
29 };
原文地址:https://www.cnblogs.com/oaoa/p/14843790.html