思路:
每层的最后一个元素,即使用层次遍历一遍。
时间复杂度O(N),空间复杂度O(N)。N为节点个数。
/**
* 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;
if(root == NULL) return ans;
queue<TreeNode*> q;
q.push(root);
TreeNode *node;
while(!q.empty()) {
int size = q.size();
for(int i = 0; i < size; ++i) {
node = q.front();
q.pop();
if(node->left) {
q.push(node->left);
}
if(node->right) {
q.push(node->right);
}
}
ans.push_back(node->val);
}
return ans;
}
};
本文介绍了一种通过层次遍历的方法来获取二叉树每一层最右侧节点值的算法实现。该方法的时间复杂度为O(N),空间复杂度也为O(N),其中N为二叉树中节点的数量。
5万+

被折叠的 条评论
为什么被折叠?



