102.二叉树的层序遍历
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:

输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1] 输出:[[1]]
示例 3:
输入:root = [] 输出:[]
提示:
- 树中节点数目在范围
[0, 2000]内 -1000 <= Node.val <= 1000
方法一:广度优先搜索
时间复杂度:O(n)
空间复杂度:O(n)
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 const ret=[]; 15 if(!root){ 16 return ret; 17 } 18 const q=[]; 19 q.push(root); 20 while(q.length!==0){ 21 const currentLevelSize = q.length; 22 ret.push([]); 23 for(let i=1;i<=currentLevelSize;++i){ 24 const node = q.shift(); 25 ret[ret.length-1].push(node.val); 26 if(node.left) q.push(node.left); 27 if(node.right) q.push(node.right); 28 } 29 } 30 return ret 31 32 };

浙公网安备 33010602011771号