199. Binary Tree Right Side View
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]
.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
queue<TreeNode*> q1,q2;
if(!root)
return ans;
q1.push(root);
while(!q1.empty()||!q2.empty())
{
while(q1.size()>0)
{
TreeNode* tmp=q1.front();
if(q1.size()==1)
ans.push_back(tmp->val);
q1.pop();
if(tmp->left)
q2.push(tmp->left);
if(tmp->right)
q2.push(tmp->right);
}
while(q2.size()>0)
{
TreeNode* tmp=q2.front();
if(q2.size()==1)
ans.push_back(tmp->val);
q2.pop();
if(tmp->left)
q1.push(tmp->left);
if(tmp->right)
q1.push(tmp->right);
}
}
return ans;
}
};
解法链接
论坛里的很好的解法,采用dfs,在树的每层只选取一个节点,未加入新节点前,该层的深度正好是vector的长度大小。
class Solution {
void dfs(vector<int>& ans,TreeNode* root, int curlev)
{
if(!root)
return;
if(curlev==ans.size())
ans.push_back(root->val);
dfs(ans,root->right,curlev+1);
dfs(ans,root->left,curlev+1);
}
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
dfs(ans,root,0);
return ans;
}
};