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

  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).
思路分析:基本就是實現BST的中序遍歷,BST中序遍歷得到有序的數組,可以容易知道第k小數,以下給出了遞歸實現,藉助counter記錄當前遍歷過的node數目,當counter==k時就可以返回。當然也可以藉助棧實現迭代的解法。
Follow up: 進一步優化,我們可以在節點中額外保留一些信息: 左子樹的大小. 在插入刪除時也同時維護左子樹的大小.進行查找時可以比較左子樹size和k的大小,就可以知道要找的node在左邊還是右邊,通過分治法的思路加速. 時間複雜度爲O(h)。
以下的僞代碼摘錄自 http://bookshadow.com/weblog/2015/07/02/leetcode-kth-smallest-element-bst/
如果BST節點TreeNode的屬性可以擴展,則再添加一個屬性leftCnt,記錄左子樹的節點個數
記當前節點爲node
當node不爲空時循環:
若k == node.leftCnt + 1:則返回node
否則,若k > node.leftCnt:則令k -= node.leftCnt + 1,令node = node.right
否則,node = node.left
上述算法時間複雜度爲O(BST的高度)

AC Code
/**
 * 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 res = 0;
    public int counter = 0;
    
    public int kthSmallest(TreeNode root, int k) {
        inOrderK(root, k);
        return res;
    }
    
    public void inOrderK(TreeNode root, int k){
        if(root.left!=null) inOrderK(root.left, k);
        counter++;
        
        if(counter == k) {
            res = root.val;
            return;
        }
        if(root.right!=null) inOrderK(root.right, k);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章