Leetcode Kth Smallest Element in a BST

OpenSoucre發表於2015-07-07

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

題目意思:

  給定一棵二叉搜尋樹,找到第k小的元素

  注意:

    1、利用二叉搜尋樹的特性

    2、修改二叉搜尋樹的節點結構

    3、最優時間複雜度是0(樹的高度)

解題思路:

方法一:

  二叉搜尋樹的特性:其中序遍歷是有序的。故中序遍歷訪問,訪問第k個元素即可。

                           

方法二:

  利用分冶的方法。

  • 統計根節點左子樹的節點個數cnt
  • 如果cnt+1 = k,則根節點即為第k個最小元素
  • 如果cnt+1 > k,則第k個最小元素在左子樹,root = root->left;
  • 如果cnt+1 < k,則第k個最小元素在右子樹,root = root->right;
  • 重複第一步

原始碼:

方法一:

 1 class Solution {
 2 public:
 3     int kthSmallest(TreeNode* root, int k) {
 4         stack<TreeNode*> nodeStack;
 5         if(root == NULL) return -1;
 6         while(true){
 7             while(root){
 8                 nodeStack.push(root);
 9                 root = root->left;
10             }
11             TreeNode* node = nodeStack.top(); nodeStack.pop();
12             if(k == 1) return node->val;
13             else root = node->right,k--;
14         }
15     }
16 };

方法二:

 1 class Solution {
 2 public:
 3     int calcNodeSize(TreeNode* root){
 4         if( root == NULL) return 0;
 5         return 1 + calcNodeSize(root->left) + calcNodeSize(root->right);
 6     }
 7     
 8     int kthSmallest(TreeNode* root, int k) {
 9         if(root == NULL) return 0;
10         int cnt = calcNodeSize(root->left);
11         if(k == cnt + 1) return root->val;
12         else if( k < cnt + 1 ) return kthSmallest(root->left,k);
13         else return kthSmallest(root->right, k-cnt-1);
14     }
15 };

 

  

相關文章