LeetCode Notes 009

Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree [1,null,2,3]

1
2
3
4
5
1
\
2
/
3

return [3,2,1]

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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/

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

dfs(root.left, ans);
dfs(root.right, ans);

ans.push(root.val);
}

var postorderTraversal = function(root) {
var ans = [];
dfs(root, ans);
return ans;
};

Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:
Given binary tree [1,null,2,3]

1
2
3
4
5
1
\
2
/
3

return [1,2,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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
function dfs(root, ans) {
if (!root) return;
ans.push(root.val);

dfs(root.left, ans);
dfs(root.right, ans);
}

var preorderTraversal = function(root) {
var ans = [];
dfs(root, ans);
return ans;
};

Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

1
2
3
4
5
   1            <---
/ \
2 3 <---
\ \
5 4 <---

You should return [1, 3, 4]

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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = 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);
}

var a = [];
ans.forEach(function(item) {
a.push(item.pop());
});

return a;
};
文章作者: Monad Kai
文章链接: onlookerliu.github.io/2018/03/14/LeetCode-Notes-009/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏