给定一棵二叉搜索树,请找出其中第 k 大的节点的值。

    示例 1:

    输入: root = [3,1,4,null,2], k = 1
    3
    / \
    1 4
    \
    2
    输出: 4
    示例 2:

    输入: root = [5,3,6,2,4,null,null,1], k = 3
    5
    / \
    3 6
    / \
    2 4
    /
    1
    输出: 4

    限制:

    1 ≤ k ≤ 二叉搜索树元素个数


    1. class Solution {
    2. public int kthLargest(TreeNode root, int k) {
    3. Deque<TreeNode> stack = new LinkedList<>();
    4. while (!stack.isEmpty() || root != null) {
    5. if (root != null) {
    6. stack.addLast(root);
    7. root = root.right;
    8. } else {
    9. root = stack.pollLast();
    10. if (--k == 0) return root.val;
    11. root = root.left;
    12. }
    13. }
    14. return -1;
    15. }
    16. }