2015年10月24日星期六

Leetcode 199 Binary Tree Right Side View

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].
Solution 1: Use BFS iterative is better way.
 public class Solution {  
   public List<Integer> rightSideView(TreeNode root) {  
     List<Integer> res=new ArrayList<>();  
     if (root==null) return res;  
     Deque<TreeNode> qu=new LinkedList<>();  
     Deque<TreeNode> next=new LinkedList<>();  
     qu.offer(root);  
     while (!qu.isEmpty()) {  
       TreeNode x=null;  
       while (!qu.isEmpty()) {  
         x=qu.poll();  
         if (x.left!=null) next.offer(x.left);  
         if (x.right!=null) next.offer(x.right);  
       }  
       res.add(x.val);  
       Deque<TreeNode> temp=qu;  
       qu=next;  
       next=temp;  
     }  
     return res;  
   }  

没有评论:

发表评论