-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinaryTreeRightSideView.java
More file actions
50 lines (38 loc) · 1.36 KB
/
Copy pathBinaryTreeRightSideView.java
File metadata and controls
50 lines (38 loc) · 1.36 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
// 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.
// See: https://leetcode.com/problems/binary-tree-right-side-view/
package leetcode.tree;
import java.util.ArrayList;
import java.util.List;
import leetcode.util.tree.TreeNode;
public class BinaryTreeRightSideView {
/**
* Solution 1: Easy initial solution.
* Time complexity: O(N), Space complexity: O(N)
*/
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ans = new ArrayList<>();
createView(root, 0, ans);
// createViewOpt(root, 0, ans);
return ans;
}
private void createView(TreeNode root, int depth, List<Integer> list) {
if (root == null) return;
if (depth < list.size())
list.set(depth, root.val);
else list.add(root.val);
createView(root.left, depth + 1, list);
createView(root.right, depth + 1, list);
}
/**
* Optimized version
*/
@SuppressWarnings("unused")
private void createViewOpt(TreeNode root, int depth, List<Integer> list) {
if (root == null) return;
if (depth == list.size())
list.add(root.val);
createViewOpt(root.right, depth + 1, list);
createViewOpt(root.left, depth + 1, list);
}
}