LeetCode 230. Kth Smallest Element in a BST

问题描述

  • Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
  • Note:
    You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.
  • Follow up:
    What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
  • 地址

问题分析

  • 该题和 剑指offer-二叉搜索树的第k个结点一样 ,求 BST的第k小的节点。
  • 利用BST中序遍历的结果便是升序序列的性质,很容易找到第K个
    • 非递归法
    • 递归法
  • 该题的 Follow up 比较有意思,说是如何该二叉树经常进行插入删除操作,也经常进行找到第k个元素的操作,那么如何快速的到第k小的元素?
    改变节点的结构,每一个节点同时存储它的左子树所有节点数目,这样便可以根据 k 与 当前根节点的大小,来选择恰好是当前根,还是第k个元素在左子树中,需递归左子树,或者第k个元素在右子树中,需递归右子树。 log(N)的时间复杂度。

代码实现

  • 非递归法
public int kthSmallest(TreeNode root, int k) {
        if (root == null || k <= 0) {
            return 0;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curNode = root;
        while (curNode != null || ! stack.isEmpty()) {
            while (curNode != null) {
                stack.push(curNode);
                curNode = curNode.left;
            }
            curNode = stack.pop();
            //看是否到第k个节点了
            if (--k == 0) {
                return curNode.val;
            }
            curNode = curNode.right;
        }
        return 0;
    }
  • 递归法
 public int kthSmallest(TreeNode root, int k) {
        if (root == null || k < 0) {
            return 0;
        }
        int[] count = new int[1]; 
        count[0] = 0;
        TreeNode res = kthSmallest(root, count, k);
        //若找到第k个节点,返回该值
        return res == null ? 0 : res.val;
    }

    // 在已经查找到了count[0]个节点之后,查找第K个节点,若找到了返回该节点,找不到,返回null
    public TreeNode kthSmallest(TreeNode root, int[] count, int k) {
        if (root == null) {
            return null;
        }
        //在左子树查找
        TreeNode leftRes = kthSmallest(root.left, count, k);
        if (leftRes != null) {//已经找到第k个节点
            return leftRes;
        }
        //尚不足k个
        if (++count[0] == k) {//当前节点
            return root;
        }
        //右子树查找
        return kthSmallest(root.right, count, k);
    }

猜你喜欢

转载自blog.csdn.net/zjxxyz123/article/details/80079504