
解法一
迭代
class Solution {
public:
int kthLargest(TreeNode* root, int k) {
stack<TreeNode*> stc;
int n=0;
while (!stc.empty() || root)
{
while (root)
{
stc.push(root);
root=root->right;
}
root=stc.top();
stc.pop();
n++;
if(n==k) return root->val;
root=root->left;
}
return 0;
}
};
解法二
递归,性能更优
class Solution {
public:
int res=0;
int n=0;
int kthLargest(TreeNode* root, int k) {
dfs(root,k);
return res;
}
void dfs(TreeNode* root, int k){
if(root==NULL) return ;
if(root->right) dfs(root->right,k);
n++;
if(n==k) res=root->val;
if(root->left) dfs(root->left,k);
return ;
}
};
本文介绍了解决二叉树中寻找第K大元素的问题,提供了两种方法:一种是使用迭代法,通过栈来实现中序遍历;另一种是采用递归法,进行逆中序遍历,这种方法性能更优。两种方法都确保了能有效地找到目标节点。
235

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



