-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreeRightSideView.java
53 lines (49 loc) · 1.62 KB
/
BinaryTreeRightSideView.java
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
/*
Given the root of 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.
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BinaryTreeRightSideView {
public static void main(String[] args) {
TreeNode root=new TreeNode(1);
root.left=null;
root.right=new TreeNode(2);
// root.right=new TreeNode(3);
// root.left.left=null;
// root.left.right=new TreeNode(5);
// root.right.left=null;
// root.right.right=new TreeNode(4);
List<Integer> ans=rightSideView(root);
System.out.println(ans);
}
public static List<Integer> rightSideView(TreeNode root) {
List<Integer> result=new ArrayList<>();
if (root==null){
return result;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
result.add(root.data);
while (!queue.isEmpty()){
int levelsize= queue.size();
List<Integer> mr=result;
int n;
for (int i = 0; i < levelsize; i++) {
TreeNode currentnode=queue.poll();
if (currentnode.right!=null){
queue.offer(currentnode.right);
n=currentnode.right.data;
result.add(currentnode.right.data);
}
}
// result.add(n);
}
return result;
}
}