题目描述
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.
样例
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
算法1
(暴力枚举) $O(n)$
层序遍历整个数,每层先遍历右子树,且将每层最右的节点放入数组。
时间复杂度
每个节点走一遍,O(n)
递归调用栈,空间复杂度O(n)
参考文献
C++ 代码
/**
* 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) {
if(!root) return {};
vector<int> res;
helper(root, 0, res);
return res;
}
void helper(TreeNode* root, int level, vector<int>& res)
{
if(!root) return;
if(level==res.size())
res.push_back(root->val);
helper(root->right, level+1, res);
helper(root->left, level+1, res);
}
};
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla