DFS
比较每个节点的深度及用字符串纪录它的位置;
也可以用用层次遍历,并且记下每层的节点;
struct Node{
int val;
string rt;
Node(int x,string y):val(x),rt(y){}
};
class Solution {
public:
void DFS(TreeNode* root,string rt,int depth,vector<Node> &vt)
{
if(!root)
return;
if(depth<vt.size())
{
if(rt>vt[depth].rt)
{
vt[depth].rt=rt;
vt[depth].val=root->val;
}
}
else
{
Node node(root->val,rt);
vt.push_back(node);
}
DFS(root->left,rt+"1",depth+1,vt);
DFS(root->right,rt+"2",depth+1,vt);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> vec;
vector<Node> vt;
DFS(root, "", 0, vt);
for(int i=0;i<vt.size();i++)
vec.push_back(vt[i].val);
return vec;
}
};
BFS
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(!root)
return res;
queue<TreeNode*> vec;
vec.push(root);
while(!vec.empty())
{
res.push_back(vec.back()->val);
int _size=vec.size();
for(int i=0;i<_size;i++)
{
TreeNode* node=vec.front();
if(node->left)
vec.push(node->left);
if(node->right)
vec.push(node->right);
vec.pop();
}
}
return res;
}
};