首页 > 其他 > 详细

Leetcode#199Binary Tree Right Side View

时间:2015-05-09 20:33:37      阅读:271      评论:0      收藏:0      [点我收藏+]

Binary Tree Right Side View

 Total Accepted: 8075 Total Submissions: 30533My Submissions

Question Solution 


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].

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

分析,直观上只需考虑最右边的元素,没有则考虑左儿子,但会出现以下状况

      1

    /  \

   2    3

  /

 4

我们的解决方案是,以层为单位,使用Queue类,只将每一层最右的节点放入结果list中


public class Solution {

    

    public List<Integer> rightSideView(TreeNode root) {

        List<Integer> x=new ArrayList<Integer>();

        Queue<TreeNode> queue = new LinkedList<TreeNode>();

        if(root!=null)

        {    

            TreeNode z=null;

            TreeNode y=null;

            queue.add(root);

            queue.add(z);

            boolean o=false;

            while(queue.peek()!=null)

            {

                o=false;

                y=queue.element();

                x.add(y.val);

                while(y!=null)

                {

                    if(y.right!=null)

                    {

                        o=true;

                        queue.add(y.right);

                    }

                    if(y.left!=null)

                    {

                        o=true;

                        queue.add(y.left);

                    }

                    

                    queue.remove();

                    y=queue.element();

                }

                if(o==true)

                    queue.add(z);

                queue.remove();

            }

        }

        return x;

    }

}


Leetcode#199Binary Tree Right Side View

原文:http://7061299.blog.51cto.com/7051299/1649852

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