HZFE / awesome-interview

剑指前端 Offer
http://febook.hzfe.org/
Other
2.33k stars 176 forks source link

二叉搜索树的第 k 大的节点-迭代写法 #34

Closed xjq7 closed 2 years ago

xjq7 commented 2 years ago
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
var kthLargest = function(root, k) {
    if(!root)return 0
    const stack=[]
    while(stack.length||root){
        while(root){
            stack.push(root)
            root=root.right
        }
        const cur=stack.pop()
        k--
        if(k===0)return cur.val
        root=cur.left
    }
    return 0
};