这道题非常的好。可以用depth-first search 以及breadth-first两种解法。参考了
并且depth-first search 不是通常意义上的前序,后以及中序遍历。并且要对depth 进行判断。
breadth-first每次访问的都是每层的最后一个元素,也就是最右边的元素。
class Solution {
public:
vector<int> ans;
void depthSearch(TreeNode* root, vector<int>& res, int level){
if(!root) return;
if(res.size() == level) res.push_back(root->val);
depthSearch(root->right, res, level+1);
depthSearch(root->left, res, level+1);
}
// this is for depth-first traverse
vector<int> rightSideView1(TreeNode* root){
int level(0);
vector<int> res;
if(!root) return res;
res.push_back(root->val);
depthSearch(root, res, level);
return res;
}
// this is for breadth-first search
vector<int> rightSideView(TreeNode* root) {
if(root == NULL) return ans;
queue<TreeNode*> nodePath;
nodePath.push(root);
TreeNode* current = new TreeNode(0);
while(!nodePath.empty()){
ans.push_back(nodePath.back()->val);
int queue_size = nodePath.size();
while(queue_size--){
current = nodePath.front(); nodePath.pop();
if(current->left) nodePath.push(current->left);
if(current->right) nodePath.push(current->right);
}
}
return ans;
}
};