[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個小的節點值。效率

相關文章
相關標籤/搜索