Repository navigation
Expand file tree
/
Copy pathproblem199.java
More file actions
105 lines (72 loc) · 2.16 KB
/
Copy pathproblem199.java
File metadata and controls
105 lines (72 loc) · 2.16 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//199. Binary Tree Right Side View
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class problem199 {
public static List<Integer> rightSideView(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if(root==null)
return ans;
Queue <TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty())
{
int sz = q.size();
for(int i=1;i<=sz;i++)
{
TreeNode curr = q.poll();
if(curr.left!=null)
q.add(curr.left);
if(curr.right!=null)
q.add(curr.right);
if(i==sz)
ans.add(curr.val);
}
}
return ans;
}
public static TreeNode buildTree(Integer[] arr) {
if (arr.length == 0 || arr[0] == null) return null;
TreeNode root = new TreeNode(arr[0]);
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < arr.length) {
TreeNode current = queue.poll();
// Left child
if (i < arr.length && arr[i] != null) {
current.left = new TreeNode(arr[i]);
queue.add(current.left);
}
i++;
// Right child
if (i < arr.length && arr[i] != null) {
current.right = new TreeNode(arr[i]);
queue.add(current.right);
}
i++;
}
return root;
}
public static void main(String[] args) {
Integer[] treeArray = {1,2,3,4,null,null,null,5};
// Construct the tree
TreeNode root = buildTree(treeArray);
System.out.println(rightSideView(root));
}
}