[Leetcode-Tree] Kth Smallest Element in a BST

Kth Smallest Element in a BST
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.node

Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.code

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:element

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).it

1.解题思路io

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

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 upclass

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

相关文章
相关标签/搜索