230. Kth Smallest Element in a BST

本文介绍了一种方法,通过中序遍历来找到二叉搜索树中的第K小元素,同时讨论了如何优化算法以适应频繁修改的二叉搜索树。通过调整遍历策略和使用额外数据结构,提高了查询效率。

题目:

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?

Hint:

    1. Try to utilize the property of a BST.
    2. What if you could modify the BST node's structure?
    3. The optimal runtime complexity is O(height of BST).

链接:  http://leetcode.com/problems/kth-smallest-element-in-a-bst/

题解:

用了比较笨的方法 - inorder traversal,做了一下剪枝。

Time Complexity - O(k), Space Complexity - O(k)。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<Integer> nodeVal = new ArrayList<Integer>();
    
    public int kthSmallest(TreeNode root, int k) {
        if(root == null)
            return 0;
        inorder(root, k);
        return nodeVal.get(k - 1);
    }
    
    private void inorder(TreeNode root, int k) {
        if(nodeVal.size() >= k)
            return;
        if(root == null)
            return;
        inorder(root.left, k);
        nodeVal.add(root.val);
        inorder(root.right, k);
        
    }
}

 

Update:

Time Complexity - O(n), Space Complexity - O(1)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    private int count = 0;
    private int res = 0;
    public int kthSmallest(TreeNode root, int k) {
        if(root == null)
            return 0;
        inorder(root, k);
        return res;
    }
    
    private void inorder(TreeNode root, int k) {
        if(root == null)
            return;
        if(count >= k)
            return;
        inorder(root.left, k); 
        if(count >= k)
            return;
        res = root.val;
        count++;
        inorder(root.right, k);
        
    }
}

 

二刷:

一开始想到是用inorder traversal,可以建立一个list, 当list.size() == k的时候我们跳出,最后返回list.get(k - 1)。 后来想到我们可以继续优化,并不需要使用list来保存结果。

Java:

Inorder traversal:

Time Complexity - O(k), Space Complexity - O(k)。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        List<Integer> res = new ArrayList<>();
        inOrder(res, root, k);
        return res.size() >= k ? res.get(k - 1) : 0;
    }
    
    private void inOrder(List<Integer> res, TreeNode root, int k) {
        if (root == null || res.size() >= k)  return;
        inOrder(res, root.left, k);
        res.add(root.val);
        inOrder(res, root.right, k);
    }
}

 

优化:

不用建立List,直接使用count来记录

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int count = 0;
    private int res = 0;
    
    public int kthSmallest(TreeNode root, int k) {
        inOrder(root, k);
        return res;
    }
    
    private void inOrder(TreeNode root, int k) {
        if (root == null || count >= k)  return;
        inOrder(root.left, k);
        count++;
        if (count == k) res = root.val;
        inOrder(root.right, k);
    }
}

 

三刷:

依然是in-order traversal,写了iterative的版本。 Follow up在查询多和更改多的情况下,我们可以为BST的每个节点增加一个int count,然后进行二分查找。

Java:

Time Complexity - O(k), Space Complexity - O(k)。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        if (root == null) return Integer.MAX_VALUE;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        stack.push(node);
        while (node != null || !stack.isEmpty()) {
            if (node != null) {
                stack.push(node);
                node = node.left;
            } else {
                node = stack.pop();
                k--;
                if (k == 0) return node.val;
                node = node.right;
            }
        }
        return root.val;
    }
}

 

 

 

Reference:

https://leetcode.com/discuss/68052/two-easiest-in-order-traverse-java

https://leetcode.com/discuss/43267/4-lines-in-c

https://leetcode.com/discuss/43464/what-if-you-could-modify-the-bst-nodes-structure

https://leetcode.com/discuss/43299/o-k-space-o-n-time-10-short-lines-3-solutions

https://leetcode.com/discuss/45684/share-my-c-iterative-alg

https://leetcode.com/discuss/43771/implemented-java-binary-search-order-iterative-recursive

 

转载于:https://www.cnblogs.com/yrbbest/p/4999289.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值