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).
题意:在BST树中,查找第k小的节点值
分类:二叉树
解法1:BST树很多问题我们都可以使用中序遍历来解决,这个也不例外
我们设置一个当前访问的元素个数cur,在中序遍历过程中,每要访问一个节点,cur加1
当cur和k相等时,这就是我们要找的节点,返回即可
利用递归来进行中序遍历,如果左子树找不到,则判断是不是当前节点,不是,则在右子树接着找
如果左子树找到了,直接返回
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/47186417