解法一
按照右孩子、父节点、左孩子的顺序遍历二叉搜索树,就可以得到一个降序序列,因此遍历的第k个结点的值为所求答案。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans;
int index;
public int kthLargest(TreeNode root, int k) {
ans = 0;
index = k;
postOrder(root);
return ans;
}
private void postOrder(TreeNode root) {
if ((index == 0) || (root == null)) {
return;
}
if (root.right != null) {
postOrder(root.right);
}
index--;
if (index == 0) {
ans = root.val;
}
if (root.left != null) {
postOrder(root.left);
}
}
}