LeetCode Notes 008

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).

For example:
Given binary tree [3,9,20,null,null,15,7],

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

return its level order traversal as:

1
2
3
4
5
[
[3],
[9,20],
[15,7]
]

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
28
29
30
31
32
33
34
35
/**
* 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 [];

var ans = []
, tmp = [root];

while (tmp.length) {
var res = []
, a = [];

for (var i = 0, len = tmp.length; i < len; i++) {
if (!tmp[i]) continue;
res.push(tmp[i].val);
a.push(tmp[i].left);
a.push(tmp[i].right);
}

tmp = a.concat();
if (res.length)
ans.push(res);
}

return ans;
};

Binary Tree Level Order Traversal II

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

For example:
Given binary tree [3,9,20,null,null,15,7],

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

return its bottom-up level order traversal as:

1
2
3
4
5
[
[15,7],
[9,20],
[3]
]

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
28
29
30
31
32
33
34
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrderBottom = function(root) {
if (!root) return [];

var ans = [], tmp = [root];

while (tmp.length) {
var res = [], _tmp = [];

tmp.forEach(function(item) {
res.push(item.val);
if (item.left)
_tmp.push(item.left);
if (item.right)
_tmp.push(item.right);
});

ans.push(res);
tmp = _tmp;
}

return ans.reverse();

};

Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1
2
3
4
5
   1
/ \
2 3
\
5

All root-to-leaf paths are:

1
["1->2->5", "1->3"]

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/

var ans, res;

function dfs(root) {
if (!root) return;

res.push(root.val);

if (!root.left && !root.right) {
var str = res.reduce(function(pre, item) {
return pre + '->' + item;
});

str = str.toString();

ans.push(str);
res.pop();
return;
}

if (root.left)
dfs(root.left);

if (root.right)
dfs(root.right);

res.pop();
}

var binaryTreePaths = function(root) {
ans = [], res = [];
dfs(root);
return ans;
};
文章作者: Monad Kai
文章链接: onlookerliu.github.io/2018/03/12/LeetCode-Notes-008/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏