【题目描述】
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.
Subscribe to see which companies asked this question
在递归的过程中,如果当前vector中的元素个数小于当前level,说明右边没有元素挡住当前遍历到的元素,将当前元素加入到vector中,反之则先右子树再左子树来遍历下一层。
【代码】
/**
* 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> vec;
void dfs(TreeNode* root,int level){
if(root==NULL) return;
if(level>vec.size()) vec.push_back(root->val);
dfs(root->right,level+1);
dfs(root->left,level+1);
}
vector<int> rightSideView(TreeNode* root) {
if(root==NULL) return {};
dfs(root,1);
return vec;
}
};