199. Binary Tree Right Side View

Problem:
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.
For example:
Given the following binary tree,
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
You should return [1, 3, 4].
Analysis:
BFS, add the last one in queue to result;
Solution:

 /**  
  * Definition for a binary tree node.  
  * public class TreeNode {  
  *   int val;  
  *   TreeNode left;  
  *   TreeNode right;  
  *   TreeNode(int x) { val = x; }  
  * }  
  */  
 class Solution {  
   public List<Integer> rightSideView(TreeNode root) {  
     Queue<TreeNode> queue = new LinkedList<>();  
     List<Integer> res = new ArrayList<>();  
     if (root == null) return res;  
     queue.offer(root);  
     while (!queue.isEmpty()) {  
     int size = queue.size();  
     for (int i = 0; i < size; i++) {  
         TreeNode cur = queue.poll();     
       if(i == size - 1) {  
          res.add(cur.val);  
       }  
      if (cur.left != null) queue.offer(cur.left);  
      if (cur.right != null) queue.offer(cur.right);  
     }  
     }  
     return res;  
   }  
 }  

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List