Skip to content

Commit 82ee28c

Browse files
committed
finish 199
1 parent bbb9eaf commit 82ee28c

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# 199. Binary Tree Right Side View
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Tree, Depth-first Search, Breadth-first Search.
5+
- Similar Questions: Populating Next Right Pointers in Each Node, Boundary of Binary Tree.
6+
7+
## Problem
8+
9+
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.
10+
11+
**Example:**
12+
13+
```
14+
Input: [1,2,3,null,5,null,4]
15+
Output: [1, 3, 4]
16+
Explanation:
17+
18+
1 <---
19+
/ \
20+
2 3 <---
21+
\ \
22+
5 4 <---
23+
```
24+
25+
## Solution 1
26+
27+
```javascript
28+
/**
29+
* Definition for a binary tree node.
30+
* function TreeNode(val) {
31+
* this.val = val;
32+
* this.left = this.right = null;
33+
* }
34+
*/
35+
/**
36+
* @param {TreeNode} root
37+
* @return {number[]}
38+
*/
39+
var rightSideView = function(root) {
40+
var queue = [{ node: root, level: 0 }];
41+
var result = [];
42+
var now = null;
43+
while (now = queue.shift()) {
44+
if (!now.node) continue;
45+
result[now.level] = now.node.val;
46+
queue.push({ node: now.node.left, level: now.level + 1 });
47+
queue.push({ node: now.node.right, level: now.level + 1 });
48+
}
49+
return result;
50+
};
51+
```
52+
53+
**Explain:**
54+
55+
nope.
56+
57+
**Complexity:**
58+
59+
* Time complexity : O(n).
60+
* Space complexity : O(n).
61+
62+
## Solution 2
63+
64+
```javascript
65+
/**
66+
* Definition for a binary tree node.
67+
* function TreeNode(val) {
68+
* this.val = val;
69+
* this.left = this.right = null;
70+
* }
71+
*/
72+
/**
73+
* @param {TreeNode} root
74+
* @return {number[]}
75+
*/
76+
var rightSideView = function(root) {
77+
var result = [];
78+
helper(root, 0, result);
79+
return result;
80+
};
81+
82+
var helper = function (node, level, result) {
83+
if (!node) return;
84+
result[level] = node.val;
85+
helper(node.left, level + 1, result);
86+
helper(node.right, level + 1, result);
87+
};
88+
```
89+
90+
**Explain:**
91+
92+
nope.
93+
94+
**Complexity:**
95+
96+
* Time complexity : O(n).
97+
* Space complexity : O(n).

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy