码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode#199Binary Tree Right Side View

时间:2015-05-09 20:36:34      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:following   example   yourself   return   values   

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

标签:following   example   yourself   return   values   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!