您的位置:首页 > 其它

Binary Tree Right Side View

2016-01-28 10:43 218 查看
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]
.

思路:dfs。每次优先遍历右子树。同时需要记录当前所处的深度,当第一次进入一个深度时,就将该值存入结果。因为我们每次都是优先遍历右子树,因此这样做一定是最右侧能看到的节点。

class Solution {
public:
void help(vector<int>& res, TreeNode* root, int depth)
{
if (!root) return;
if (res.size() < depth + 1)
res.push_back(root->val);
help(res, root->right, depth + 1);
help(res, root->left, depth + 1);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
help(res, root, 0);
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: