递归:
中序反向遍历,先遍历右子树,再遍历左子树,因为中序正向遍历时得到的二叉搜索树的结果集是升序数组,
反向则是降序,符合题目的第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 {
public:
int kthLargest(TreeNode* root, int k) {
int res;
InorderTraversal(root, k, res);
return res;
}
void InorderTraversal(TreeNode* root, int& k, int& res)
{
if (!root) return;
InorderTraversal(root->right, k, res);
if (!--k) res = root->val;
InorderTraversal(root->left, k, res);
}
};
递归提前停止:
/**
* 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:
int kthLargest(TreeNode* root, int& k) {
if (!root) return 0;
int res = kthLargest(root->right, k);
if (!--k) return root->val;
return k <= 0 ? res : 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 {
public:
int kthLargest(TreeNode* root, int& k) {
vector<TreeNode*> s;
while (root || !s.empty()) {
if (root) {
s.push_back(root);
root = root->right;
}
else {
root = s.back();
s.pop_back();
if (!--k) return root->val;
root = root->left;
}
}
return 0;
}
};