LeetCode - the kth largest node of the binary search tree (inverse midorder + count)

Topic description

image.png

Topic interpretation

The topic Let us find the Kth largest node of the binary search tree, we must first understand the following questions:

  • RQ: What is the difference between a binary search tree and an ordinary binary tree?

The characteristic of a binary search tree is that the left child nodes are smaller than the root node, and the right child nodes are larger than the root node.

Problem solving ideas

According to the characteristics of the search binary tree, we can perform an inverse in-order traversal. We all know that in-order traversal is a left-root-right traversal method, then inverse in-order traversal, as the name implies, is a right-root-left traversal method. The advantage of this traversal is that it is the same as two The fork search tree is combined, and the first right child node traversed is the first largest element, so we can use the counter method, once the counter reaches K, the node at this time is the K largest node.

var kthLargest = function(root, k) {
    
    
    // 实现逆中序遍历 + count
    let cur = root;
    const stack = [];
    const res = [];
    let count = 0;
    while (stack.length || cur) {
    
    
        while (cur) {
    
    
            stack.push(cur);
            cur = cur.right;
        }
        let node = stack.pop();
        res.push(node.val);
        count++;
        if (count === k) return node.val;
        if (node.left) {
    
    
            cur = node.left;
        }
    }
};

Summarize

There are many solutions to the problem of binary search tree. This time, the method of combining inverse inorder traversal and counter is used to find the Kth largest node. This problem also requires us to understand the characteristics of binary search tree. , The method of in-order traversal must have a certain understanding.

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/123306478