码迷,mamicode.com
首页 > 编程语言 > 详细

[JAVA]LeetCode199 Binary Tree Right Side View

时间:2015-04-09 22:02:12      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:leetcode   tree   

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].
题目的含义是:从右边看,我们能看到的节点有哪些,相当于几何中投影的概念。
解题思路:1)深度遍历,先记录右边节点的最大高度。只有大于最大高度的节点才能打印出来。(我们自己思维去判断的时候,应该更倾向这种逻辑)
2)层次遍历,将最右边的节点存入list表中。这种想法写程序更容易理解。
实现1)思路代码如下所示:

 public List<Integer> rightSideView(TreeNode root) {
        Stack<TreeNode> stack=new Stack<TreeNode>();
        Stack<TreeNode> stack1=new Stack<TreeNode>();//存储所有的节点,用来计算节点所在的高度
        List<Integer> list=new ArrayList<Integer>();
        TreeNode current=root;
        int curHeight=1;
        int rightHeight=0;
        while(current!=null||!stack.isEmpty())
        {
            if(current!=null)
            {
            if(curHeight>rightHeight)
            {
                list.add(current.val);
            }
            stack.push(current);
            stack1.push(current);
            current=current.right;
            ++curHeight;
            }else
            {
               current=stack.pop();
               //计算当前current节点所在的height值
               while(!stack1.isEmpty())
               {
                   if(stack1.peek()==current)
                   {
                       curHeight=stack1.size();
           if(curHeight>rightHeight)rightHeight=curHeight;
                       break;
                   }
                   stack1.pop();
               }
               current=current.left;
               ++curHeight;
            }
        }
        return list;
    }

实现2)思路程序如下:

 public List<Integer> rightSideView(TreeNode root) {
       List<Integer> list=new ArrayList<Integer>();
       if(root==null)return list;
       Queue<TreeNode> queue=new LinkedList<TreeNode>();
       TreeNode current=root;
       queue.offer(current);
       queue.offer(null);//相当于用null来做每层节点的间隔符
       while(!queue.isEmpty())
       {
         current=queue.poll();
         if(current!=null)
         {
            if(queue.peek()==null)
            {
                list.add(current.val);
            }
            if(current.left!=null)queue.add(current.left);
           if(current.right!=null)queue.add(current.right);
         }else
         {
            if(queue.isEmpty())
            {
                break;
            }else
            {
                queue.add(null);
            }
         }
       }
       return list;
    }

[JAVA]LeetCode199 Binary Tree Right Side View

标签:leetcode   tree   

原文地址:http://blog.csdn.net/fumier/article/details/44964411

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