解法一

按照右孩子、父节点、左孩子的顺序遍历二叉搜索树,就可以得到一个降序序列,因此遍历的第k个结点的值为所求答案。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. int ans;
  12. int index;
  13. public int kthLargest(TreeNode root, int k) {
  14. ans = 0;
  15. index = k;
  16. postOrder(root);
  17. return ans;
  18. }
  19. private void postOrder(TreeNode root) {
  20. if ((index == 0) || (root == null)) {
  21. return;
  22. }
  23. if (root.right != null) {
  24. postOrder(root.right);
  25. }
  26. index--;
  27. if (index == 0) {
  28. ans = root.val;
  29. }
  30. if (root.left != null) {
  31. postOrder(root.left);
  32. }
  33. }
  34. }