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]
.
思路:这是一个遍历问题,优先级为根右左,但是并不是所有根结点都要加入res,只有当该结点所处的层数,比当前的已经有的看到的结点个数大1时,才可以被看得见,才可以加入res。
/**
* 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> res;
if (root == NULL)
return res;
rightSideView(root, res, 1);
return res;
}
private:
void rightSideView(TreeNode* root, vector<int>& res, int level){//根右左的遍历顺序
if (root == NULL)
return;
if (level == res.size() + 1){
res.push_back(root->val);
}
rightSideView(root->right, res, level + 1);
rightSideView(root->left, res, level + 1);
}
};