Voyz's Studio.

LeetCode算法笔记--二叉树的层序遍历

字数统计: 219阅读时长: 1 min
2020/12/26 Share

LeetCode算法笔记-Day51

102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
Given binary tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7

return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

Analyse:

递归

想到递归,我们一般先想到DFS。我们可以对该二叉树进行先序遍历(根左右的顺序),同时,记录节点所在的层次level,并且对每一层都定义一个数组,然后将访问到的节点值放入对应层的数组中。  

My Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 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) {
let res = [];
if(!root) return res;

let dfs = (node,level)=>{
if(!!node){
if(res.length <= level) res.push([]);
res[level].push(node.val);
dfs(node.left,level+1);
dfs(node.right,level+1);
}
}

dfs(root,0);
return res;
};
CATALOG
  1. 1. LeetCode算法笔记-Day51
    1. 1.1. 102. Binary Tree Level Order Traversal
    2. 1.2. Analyse:
      1. 1.2.1. 递归
      2. 1.2.2. My Answer: