实现思路
总体思路是要压入节点及层数,层数其实就是该节点的父节点的层数+1
实现代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> re;
if(!root) return re;
queue<pair<TreeNode*,int>> q;
q.push(make_pair(root,0));
while(!q.empty()){
TreeNode *t=q.front().first;
int depth=q.front().second;
q.pop();
if(t->left!=nullptr) q.push(make_pair(t->left,depth+1));
if(t->right!=nullptr) q.push(make_pair(t->right,depth+1));
//注意vector的size是无符号整数
if((int(re.size())-1)<depth)
{
re.push_back(t->val);
}
else re[depth]=t->val;
}
return re;
}
};
提交结果及分析
时间复杂度O(n)