方法1:中序反向遍历,找到后还会继续遍历
class Solution {
public:
int kthLargest(TreeNode* root, int k) {
int result = 0;
dfs(root, result, k);
return result;
}
private:
void dfs(TreeNode *root, int &result, int &k) {
if (!root) return;
dfs(root->right, result, k);
if (!--k) result = root->val;
dfs(root->left, result, k);
}
};
方法2:遍历到后就停止
class Solution {
public:
int kthLargest(TreeNode* root, int &k) {
if (!root) return 0;
int result = kthLargest(root->right, k);
if (!--k) return root->val;
return k < 0 ? result : kthLargest(root->left, k);
}
};
/**
* 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 {
private:
int res;
int k;
public:
int kthLargest(TreeNode* root, int k) {
this->k = k;
dfs(root);
return res;
}
void dfs(TreeNode* curr)
{
if (curr != nullptr)
{
dfs(curr->right);
// 正好是第k个,则更新res
if (--k == 0)
{
res = curr->val;
return;
}
dfs(curr->left);
}
}
};
方法3:非递归方式
class Solution {
public:
int kthLargest(TreeNode* root, int k) {
vector<TreeNode*> worker;
while (root || worker.size()) {
while (root) {
worker.push_back(root); // 根入栈
root = root->right; // 访问右子树,向下探
}
root = worker.back(), worker.pop_back(); // 出栈
if (!--k) return root->val;
root = root->left; // 访问左子树
}
return 0;
}
};