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.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---'
方法1: dfs
思路:
(错误的思路,并不是) 实际上要返回的就是第一条dfs的路径,沿途记下所有途径节点值,到叶节点之后就可以结束了(right view可以来自多条路径的组合,如果自右至左一条比一条长)。
(正确的) preorder,dfs中传递一个level, 只有当result大小被第一次拓展,才将该节点记录。
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
rightHelper(root, result, 0);
return result;
}
void rightHelper(TreeNode * root, vector<int> & result, int depth){
if (!root) return;
if (result.size() == depth) result.push_back(root -> val);
rightHelper(root -> right, result, depth + 1);
rightHelper(root -> left, result, depth + 1);
return;
}
};
方法2: bfs
思路:
层序遍历,仅把第n个数推进result。
// 方法2: BFS, 在获取层大小后,当且仅当第n次pop才push_back到result
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
if (!root) return {};
queue<TreeNode*> q;
vector<int> res;
q.push(root);
while(!q.empty()) {
int sz = q.size();
while (sz-- > 0) {
TreeNode * top = q.front();
q.pop();
if (sz == 0) res.push_back(top -> val);
if (top -> left) q.push(top -> left);
if (top -> right) q.push(top -> right);
}
}
return res;
}
};