题目:
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:
- 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).
树的中序遍历。如果可以修改树的节点,则加入每个节点左子树的节点个数,则可以将时间复杂度降低为O(h),h为树的高度。
C++版:
/**
* 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) {
stack<TreeNode*> s;
TreeNode* current = root;
int count = 0;
while(current || s.size() != 0) {
if(current) {
s.push(current);
current = current->left;
} else {
current = s.top();
s.pop();
if(++count == k)
return current->val;
current = current->right;
}
}
}
};Java版:
/**
* 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 kthSmallest(TreeNode root, int k) {
Stack<TreeNode> s = new Stack<TreeNode>();
int count = 0;
TreeNode current = root;
while(current != null || !s.empty()) {
if(current != null) {
s.push(current);
current = current.left;
} else {
current = s.pop();
if(++count == k)
return current.val;
current = current.right;
}
}
return 0;
}
}Python版:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {integer} k
# @return {integer}
def kthSmallest(self, root, k):
node, count, current = [], 0, root
while current != None or len(node) != 0:
if current != None:
node.append(current)
current = current.left
else:
current = node[len(node) - 1]
node.pop()
count += 1
if count == k:
return current.val
current = current.right
375


: Different Ways to Add Parentheses&spm=1001.2101.3001.11974&articleId=47316151&d=1&t=3&u=e251901eb84147508a506053f5cd8150)

被折叠的 条评论
为什么被折叠?



