[leetcode][BST] Kth Smallest Element in a BST

来源:互联网 发布:奢侈品销售 知乎 编辑:程序博客网 时间:2024/05/16 15:35

题目:

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).
基本解法:O(n),其中n为BST的节点个数
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:int kthSmallest(TreeNode* root, int k) {if (NULL == root || k < 1) return -1;//非法输入,应抛出异常的stack<TreeNode *> sta;TreeNode *p = root;int cnt = 0;while (p != NULL || !sta.empty()){while (p != NULL){//一路向左sta.push(p);p = p->left;}//visitTreeNode *q = sta.top();sta.pop();if (++cnt == k) return q->val;p = q->right;}}};

优化解法:

思路:在节点数据结构中增加一个表示在BST中该节点左边的节点个数的int型成员lCnt

插入:在查找节点插入位置的过程中,如果该节点应该放在当前节点的左边,则当前节点的lCnt加1,找到该节点的合适位置时,该节点的lCnt为0

删除:在查找删除节点的过程中,如果该节点值小于当前节点值,则当前节点的lCnt减1

查找:如果k小于当前节点的lCnt,到当前节点的左边继续查找;否则到当前节点的右边继续查找k=k-cur->lCnt-1

实现:待续

0 0
原创粉丝点击