/
RightViewOfBinaryTree
80 lines (49 loc) · 1.64 KB
/
RightViewOfBinaryTree
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//Level Order Traversal of Tree
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> Q = new ArrayDeque<>();
Q.add(root);
while(!Q.isEmpty()){
int n = Q.size();
for(int i = 0 ; i < n ; i++){
TreeNode temp = Q.remove();
if(temp.left != null)
Q.add(temp.left);
if(temp.right != null)
Q.add(temp.right);
if(i == n-1){
res.add(temp.val);
}
}
}
return res;
}
}
//Another Approach
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
rightSideView(res , root , 1);
return res;
}
void rightSideView(List<Integer> res ,TreeNode root , int level){
if(root == null) return;
if(res.size() < level ){
res.add(root.val);
}
rightSideView(res , root.right , level+1);
rightSideView(res , root.left , level+1);
}
}