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]
.
题目要求:自上而下输出从右边往左边观察到的二叉树的结点。
思路:从右边开始添加,如果当前结点的高度height大于当前的最大高度,则将该结点加入vector。需要注意的是,由于每个高度只取最前面的结点,因此当前的最大高度为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> rightSideView(TreeNode* root) {
vector<int>result;
f(root,result,0);
return result;
}
void f(TreeNode* node,vector<int> &result, int height){
if(node == NULL)
return ;
else
height++;
if(height > result.size())
result.push_back(node->val);
f(node->right,result,height);
f(node->left,result,height);
}
};