剑指OFFER----面试题54. 二叉搜索树的第k大节点

链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int kthLargest(TreeNode root, int k) {
        int cnt = 1;
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.empty()) {
            while (root != null) {
                stack.push(root);
                root = root.right;
            }
            TreeNode cur = stack.pop();
            if (cnt == k) return cur.val;
            cnt++;
            root = cur.left;
        }
        return 0;
    }
}

猜你喜欢

转载自www.cnblogs.com/clown9804/p/12455083.html