首页 > 其他 > 详细

199. Binary Tree Right Side View

时间:2016-07-10 12:38:03      阅读:231      评论:0      收藏:0      [点我收藏+]
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.LinkedList;
import java.util.Queue;
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res=new ArrayList<Integer>();
        if(root==null)
            return res;

        
        
        Queue<TreeNode> current=new LinkedList<TreeNode>();
        
        current.offer(root);
        
        int last=0;
        
        Queue<TreeNode> next=new LinkedList<TreeNode>();
        
        while(!current.isEmpty()||!next.isEmpty())
        {
            if(!current.isEmpty())
            {
                
                TreeNode temp=current.poll();
                last=temp.val;
                if(temp.left!=null)
                    next.offer(temp.left);
                if(temp.right!=null)
                    next.offer(temp.right);
                    
            }
            else
            {
                res.add(last);
                while(!next.isEmpty())
                    current.offer(next.poll());
                
            }
        }
        
        res.add(last);
        return res;
        
    }
}

 

199. Binary Tree Right Side View

原文:http://www.cnblogs.com/aguai1992/p/5657440.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!