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改進(jìn)的先序遍歷,參數(shù)中使用level標(biāo)識層數(shù)):
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);
}