题目:
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.
思路:
先序遍历(先右后左)。max表示已经访问的最大深度,只有比这个max更大时才会保存到ret数组(答案都放在这里)中。
代码实现:
submit一次就过了:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void f(TreeNode *root, int i, int &max, vector<int> &ret){
if (root == nullptr){
return ;
}
if (i > max){
max = i;
ret.push_back(root->val);
}
f(root->right, i+1, max, ret);
f(root->left, i+1, max, ret);
}
vector<int> rightSideView(TreeNode* root) {
int max = -1;
vector<int> ret;
f(root, 0, max, ret);
return ret;
}
};