LeetCode OJ: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].

其实题目的意思就是相当于二叉树每一行的最右边的一个元素,那么简单,先bfs后取每一个数组的最后一位数就可以了,代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> rightSideView(TreeNode* root) {
13         int dep = -1;
14         bfs(root, dep + 1);
15         vector<int> res;
16         for(int i = 0; i < ret.size(); ++i){
17             res.push_back(ret[i][ret[i].size() - 1]);
18         }
19         return res;
20     }
21 
22     void bfs(TreeNode * root, int depth)
23     {
24         if(root == NULL) return;
25         if(depth < ret.size()){
26             ret[depth].push_back(root->val);
27         }else{
28             vector<int>tmp;
29             ret.push_back(tmp);
30             ret[depth].push_back(root->val);
31         }
32         if(root->left)
33             bfs(root->left, depth + 1);
34         if(root->right)
35             bfs(root->right, depth + 1);
36     }
37 private:
38     vector<vector<int>> ret;
39 };

 java版本的代码如下所示,同样是BFS之后再取最后一位组成一个数组:

 1 public class Solution {
 2     public List<Integer> rightSideView(TreeNode root) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         List<Integer> res = new ArrayList<Integer>();
 5         if(root == null)
 6             return res;
 7         bfs(ret, root, 0);
 8         for(int i = 0; i < ret.size(); ++i){
 9             res.add(ret.get(i).get(ret.get(i).size() - 1));
10         }
11         return res;
12     }
13     
14     public void bfs(List<List<Integer>> ret, TreeNode root, int dep){
15         if(ret.size() <= dep){
16             ret.add(new ArrayList<Integer>());
17         }
18         ret.get(dep).add(root.val);
19         if(root.left != null)
20             bfs(ret, root.left, dep + 1);
21         if(root.right != null)
22             bfs(ret, root.right, dep + 1);
23     }
24 }

 

posted @ 2015-10-24 11:27  eversliver  阅读(245)  评论(0编辑  收藏  举报