代码改变世界

[LeetCode]Binary Tree Right Side View

2015-04-06 17:36  庸男勿扰  阅读(187)  评论(0编辑  收藏  举报

原题链接:https://leetcode.com/problems/binary-tree-right-side-view/

题意描述:

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  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<Integer> rightSideView(TreeNode root) {
12         List<Integer> res = new ArrayList<Integer>();
13         if(root==null)
14             return res;
15         Queue<TreeNode> Q = new LinkedList<TreeNode>(); 
16         Q.offer(root);
17         int curLevel = 1;
18         res.add(root.val);
19         while(!Q.isEmpty()){
20             int levelSize = Q.size();
21             int count = 0;
22             TreeNode last = null;
23             while(count<levelSize){
24                 TreeNode p = Q.poll();
25                 if(p.left!=null){
26                     last = p.left;
27                     Q.offer(p.left);
28                 }
29                 if(p.right!=null){
30                     last = p.right;
31                     Q.offer(p.right);
32                 }
33                 count++;
34             }
35             if(last!=null)
36                 res.add(last.val);
37             
38         }
39         return res;
40     }
41 }