所有求树的边界,最优都是O(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:
void dfs(TreeNode* now,vector<int>& ans,int level){
if(level >= ans.size()) ans.push_back(now->val);
else ans[level] = now->val;
if(now->left != NULL) dfs(now->left,ans,level+1);
if(now->right != NULL) dfs(now->right,ans,level+1);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
if(root != NULL) dfs(root,ans,0);
return ans;
}
};
本文介绍了一种求解树的右视图的算法,通过深度优先搜索(DFS)遍历二叉树,记录每一层最右侧节点的值,最终得到从顶部到底部的最右侧节点值列表。此算法的时间复杂度为O(N),其中N为树中节点的数量。
483

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



