-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-right-side-view.js
More file actions
80 lines (62 loc) · 1.87 KB
/
binary-tree-right-side-view.js
File metadata and controls
80 lines (62 loc) · 1.87 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Problem: Binary Tree Right Side View
* Link: https://leetcode.com/problems/binary-tree-right-side-view/
* Difficulty: Medium
*
* Given the root of a binary tree, return the values of the nodes you can see
* ordered from top to bottom when looking from the right side.
*
* Example: root = [1,2,3,null,5,null,4] => Output: [1,3,4]
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*/
// JavaScript Solution - BFS (Level Order Traversal)
function rightSideView(root) {
if (!root) return [];
const result = [];
const queue = [root];
while (queue.length) {
const levelSize = queue.length;
for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
// Last node in current level is visible from the right
if (i === levelSize - 1) result.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return result;
}
// DFS approach - track depth, visit right first
function rightSideViewDFS(root) {
const result = [];
function dfs(node, depth) {
if (!node) return;
// First node we see at this depth (from the right) gets added
if (depth === result.length) result.push(node.val);
dfs(node.right, depth + 1); // visit right first
dfs(node.left, depth + 1);
}
dfs(root, 0);
return result;
}
module.exports = rightSideView;
/* Python Solution:
from collections import deque
def rightSideView(root):
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
# Last node in level is visible from right
if i == level_size - 1:
result.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return result
*/