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]
.
代码自己体会:
/**
* 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> rightvalue;
int level = 0;
vector<int> rightSideView(TreeNode* root) {
if(root)
down(root, 0);
return rightvalue;
}
void down(TreeNode *node, int N)
{
if(N >= level)
{
rightvalue.push_back(node->val);
level++;
}
N++;
if(node->right) down(node->right, N);
if(node->left) down(node->left, N);
}
};