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?

Hint:

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

1.解题思路

本题需要找的是第k小的节点值,而二叉搜索树的中序遍历正好是数值从小到大排序的,那么这题就和中序遍历一个情况。

public class Solution {
    Stack<TreeNode> s=new Stack<TreeNode>();
    public int kthSmallest(TreeNode root, int k) {
        if(root==null) return 0;
        pushLeft(root);
        while(!s.empty()){
            TreeNode node=s.pop();
            if(--k==0) return node.val;
            if(node.right!=null)
                pushLeft(node.right);
        }
        return 0;
    }
    private void pushLeft(TreeNode root){
        TreeNode node=root;
        while(node!=null){
            s.push(node);
            node=node.left;
        }
    }
}

3.Follow up

如果树会经常被更改,为了效率,我们可以对树的构造稍作变更,添加一个属性,来标明该节点拥有的左子树的节点数,而这个Number就是比当前值小的节点个数,这样我们结合二分法,就很容易找到第k个小的节点值。


tiffanytown
6 声望2 粉丝

keep learning