剑指 Offer 54. 二叉搜索树的第k大节点

给定一棵二叉搜索树,请找出其中第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 ≤ 二叉搜索树元素个数

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof

多题一解 参照https://www.cnblogs.com/xxxsans/p/13304954.html

1)二叉搜索树的性质,root 大于左子树,小于右子树,如果右子树的节点是 k-1,那么 root 就是结果,否则如果右子树节点数目小于 K-1,那么结果就在左子树,否则就在右子树。

/**
 * 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}
 */
function Count(node){
    if(node===null)return 0;
    const l=Count(node.left);
    const r=Count(node.right);
    return l+r+1;
}
var kthLargest = function(root, k) {
    const r=Count(root.right);
    if(r===k-1)return root.val;
    else if(r<k-1)return kthLargest(root.left,k-r-1);
    return kthLargest(root.right,k);
};

2)中序遍历一个二叉查找树(BST)的结果是一个有序数组,因此只需要在遍历到第k个,返回当前元素即可

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def kthLargest(self, root: TreeNode, k: int) -> int:
        result = []
        stack = [(1, root)]
        while stack:
            go_deeper, node = stack.pop()
            if node is None:
                continue
            if go_deeper:
                # 左右节点还需继续深化,并且入栈是先右后左
                stack.append((1, node.right))
                # 节点自身已遍历,回头可以直接取值
                stack.append((0, node))
                stack.append((1, node.left))
            else:
                result.append(node.val)
        return result[::-1][k-1]

 

posted @ 2020-08-25 11:29  XXXSANS  阅读(167)  评论(0编辑  收藏  举报