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后取每一个数组的最后一位数就可以了,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
int dep = -;
bfs(root, dep + );
vector<int> res;
for(int i = ; i < ret.size(); ++i){
res.push_back(ret[i][ret[i].size() - ]);
}
return res;
} void bfs(TreeNode * root, int depth)
{
if(root == NULL) return;
if(depth < ret.size()){
ret[depth].push_back(root->val);
}else{
vector<int>tmp;
ret.push_back(tmp);
ret[depth].push_back(root->val);
}
if(root->left)
bfs(root->left, depth + );
if(root->right)
bfs(root->right, depth + );
}
private:
vector<vector<int>> ret;
};
java版本的代码如下所示,同样是BFS之后再取最后一位组成一个数组:
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
List<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
bfs(ret, root, );
for(int i = ; i < ret.size(); ++i){
res.add(ret.get(i).get(ret.get(i).size() - ));
}
return res;
} public void bfs(List<List<Integer>> ret, TreeNode root, int dep){
if(ret.size() <= dep){
ret.add(new ArrayList<Integer>());
}
ret.get(dep).add(root.val);
if(root.left != null)
bfs(ret, root.left, dep + );
if(root.right != null)
bfs(ret, root.right, dep + );
}
}