首页 > 其他 > 详细

199. Binary Tree Right Side View

时间:2016-06-08 10:26:45      阅读:120      评论:0      收藏:0      [点我收藏+]
    /*
     * 199. Binary Tree Right Side View 
     * 11.21 By Mingyang 
     * 在recursive的算法,就是贴着树的右边界往下面走,如果不行往左边偏一个,然后继续往右边偏,利用末尾的个数与层数相等的技巧
     * 其实是一种根右左的算法,很巧妙
     */    
    public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            rightSideView(root, result, 0);
            return result;
        }
    public void rightSideView(TreeNode curr, List<Integer> result, int currDepth){
            if(curr == null){
                return;
            }
            //这里就是最精妙的地方,利用result的数量跟层数相等的方法,比如root的右子树走完了以后
            //走左边的时候,刚开始没有到达这个条件,就自然继续往下走
            if(currDepth == result.size()){
                result.add(curr.val);
            }
            rightSideView(curr.right, result, currDepth + 1);
            rightSideView(curr.left, result, currDepth + 1);
        }

 

199. Binary Tree Right Side View

原文:http://www.cnblogs.com/zmyvszk/p/5569188.html

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