Skip to content

Commit 40b7f0c

Browse files
binary tree right side view
1 parent f7fc946 commit 40b7f0c

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package medium;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedList;
5+
import java.util.List;
6+
import java.util.Queue;
7+
8+
import classes.TreeNode;
9+
10+
/**199. Binary Tree Right Side View
11+
12+
Total Accepted: 50496
13+
Total Submissions: 138613
14+
Difficulty: Medium
15+
16+
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.
17+
18+
For example:
19+
Given the following binary tree,
20+
21+
1 <---
22+
/ \
23+
2 3 <---
24+
\ \
25+
5 4 <---
26+
27+
You should return [1, 3, 4]. */
28+
public class BinaryTreeRightSideView {
29+
//Using BFS is pretty straightforward. But there might be a smarter way.
30+
public List<Integer> rightSideView(TreeNode root) {
31+
List<Integer> res = new ArrayList<Integer>();
32+
if(root == null) return res;
33+
Queue<TreeNode> q = new LinkedList<TreeNode>();
34+
q.offer(root);
35+
while(!q.isEmpty()){
36+
int currentSize = q.size();
37+
int i = 0;
38+
for(; i < currentSize-1; i++){
39+
TreeNode currentNode = q.poll();
40+
if(currentNode.left != null) q.offer(currentNode.left);
41+
if(currentNode.right != null) q.offer(currentNode.right);
42+
}
43+
TreeNode currentNode = q.poll();
44+
if(currentNode.left != null) q.offer(currentNode.left);
45+
if(currentNode.right != null) q.offer(currentNode.right);
46+
res.add(currentNode.val);
47+
}
48+
return res;
49+
}
50+
51+
public static void main(String...strings){
52+
BinaryTreeRightSideView test = new BinaryTreeRightSideView();
53+
TreeNode root = new TreeNode(1);
54+
root.left = new TreeNode(2);
55+
root.right = new TreeNode(3);
56+
root.left.right = new TreeNode(5);
57+
root.right.right = new TreeNode(4);
58+
List<Integer> result = test.rightSideView(root);
59+
for(int i : result){
60+
System.out.print(i + ", ");
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)