您的位置:首页 > 其它

右侧视角的二叉树

2016-08-19 16:31 225 查看
这题本来是不想使用遍历来做的,但是如果不这样的话也不知道这个树的高度,那么还是直接使用层序来做吧,代码如下:

class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
int dep = -1;
bfs(root, dep + 1);
vector<int> res;
for(int i = 0; i < ret.size(); ++i){
res.push_back(ret[i][ret[i].size() - 1]);
}
return res;
}

void bfs(TreeNode * root, int depth)
{
if(root == NULL) return;
if(depth < ret.size()){
ret[depth].push_back(root->val);
}else{
vector<int>tmp;
ret.push_back(tmp);
ret[depth].push_back(root->val);
}
if(root->left)
bfs(root->left, depth + 1);
if(root->right)
bfs(root->right, depth + 1);
}
private:
vector<vector<int>> ret;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: