File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ // id: 199
2+ // Name: Binary Tree Right Side View
3+ // link: https://leetcode.com/problems/binary-tree-right-side-view/
4+ // Difficulty: Medium
5+
6+ class Solution {
7+ public List <Integer > rightSideView (TreeNode root ) {
8+ // right side view means the rightmost element of each level
9+
10+ List <Integer > result = new ArrayList <>();
11+
12+ Queue <TreeNode > q = new LinkedList <>();
13+ if (root != null ) {
14+ q .add (root );
15+ }
16+
17+ while (!q .isEmpty ()) {
18+ int count = q .size ();
19+ // traverse the complete level
20+ while (count > 0 ) {
21+ root = q .poll ();
22+
23+ if (root .left != null ) {
24+ q .add (root .left );
25+ }
26+ if (root .right != null ) {
27+ q .add (root .right );
28+ }
29+ count --;
30+ }
31+ // add the last level to the result
32+ result .add (root .val );
33+ }
34+
35+ return result ;
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments