199. Binary Tree Right Side View
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> rightSideView(TreeNode* root) {
vector<int> res;
dfs(root, res);
return res;
}
void dfs(TreeNode* root, vector<int> &res){
if(root==NULL) return;
stack<pair<TreeNode*, int>> stk;
stk.push(make_pair(root,0));
TreeNode* cur = root;
int level = 0;
while(!stk.empty()){
cur = stk.top().first;
level = stk.top().second;
stk.pop();
if(level>=res.size()) res.push_back(cur->val);
if(cur->left!=NULL) stk.push(make_pair(cur->left, level+1));
if(cur->right!=NULL) stk.push(make_pair(cur->right, level+1));
}
}
};