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);
}
};