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].
解法一(层序遍历BFS):
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(root == NULL) return res;
queue<TreeNode*> que;
int cnt = 1, num = 0;
que.push(root);
while(!que.empty()){
res.push_back(que.front() -> val);
for(int i = 0; i<cnt; i++){
TreeNode* tmp = que.front();
que.pop();
if(tmp -> right){
que.push(tmp -> right);
num++;
}
if(tmp -> left){
que.push(tmp -> left);
num++;
}
}
cnt = num;
num = 0;
}
return res;
}
解法二(DFS改进的先序遍历,参数中使用level标识层数):
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
dfs(root, 1, res);
return res;
}
void dfs(TreeNode* root, int level, vector<int>& res) {
if(root == NULL) return;
if(level > res.size()) res.push_back(root -> val);
dfs(root -> right, level+1, res);
dfs(root -> left, level+1, res);
}
网友评论