-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path199.binary-tree-right-side-view.ts
67 lines (54 loc) · 1.35 KB
/
199.binary-tree-right-side-view.ts
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
function rightSideViewBFS(root: TreeNode | null): number[] {
const view: number[] = [];
const queue = [root];
while (queue.length !== 0) {
const levelLength = queue.length;
let rightNode: TreeNode | null = null;
for (let i = 0; i < levelLength; i++) {
const node = queue.shift();
if (node) {
rightNode = node;
queue.push(node.left);
queue.push(node.right);
}
}
if (rightNode) {
view.push(rightNode.val);
}
}
return view;
}
function rightSideViewDFS(root: TreeNode | null): number[] {
const view = [];
function dfs(root: TreeNode | null, level: number) {
if (root === null) {
return;
}
view[level] = root.val;
if (root.left) {
dfs(root.left, level + 1);
}
if (root.right) {
dfs(root.right, level + 1);
}
}
dfs(root, 0);
return view;
}
const tree = new TreeNode(
1,
new TreeNode(2, new TreeNode(4), new TreeNode(5)),
new TreeNode(3)
);
console.log(rightSideViewBFS(tree));
console.log(rightSideViewDFS(tree));