leetcode -- Kth Smallest Element in a BST -- 简单重点
来源:互联网 发布:sqlite 创建数据库 编辑:程序博客网 时间:2024/06/15 04:37
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
这里注意 BST的left subtree 所有**node都要小于root, right subtree 所有node都要大于**root。没有等于,并且是所有node
思路1 非递归用stack
用inorder的模板就行
class Solution(object): def inorder(self, root, res, k): stack = [] while stack or root: if root: stack.append(root) root = root.left else: root = stack.pop() res.append(root) if len(res) == k: return root.val root = root.right def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ return self.inorder(root, [], k)
思路2 递归
计算一个树的node个数,
参考http://www.rainatian.com/2015/07/06/leetcode-python-java-kth-smallest-element-in-a-bst/
class Solution(object): def SizeOfTree(self, root): if root is None: return 0 return self.SizeOfTree(root.left) + self.SizeOfTree(root.right) + 1 def kthSmallest(self, root, k): if root is None: return 0 leftsize = self.SizeOfTree(root.left) if leftsize == k-1: return root.val elif leftsize > k-1: return self.kthSmallest(root.left,k) else: return self.kthSmallest(root.right,(k-1-leftsize))
这个效率还没有非递归高,
思路3 O(BST的高度)
第二遍的时候再看
参考
http://bookshadow.com/weblog/2015/07/02/leetcode-kth-smallest-element-bst/
0 0
- leetcode -- Kth Smallest Element in a BST -- 简单重点
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- 轻量级JavaEE企业应用实战(十一)
- 231. Power of Two
- ListView+BaseAdapter的使用方法
- 免费公开课视频《神马是数据科学家?》
- iPhone/iOS开发推送C++服务端APNS源代码
- leetcode -- Kth Smallest Element in a BST -- 简单重点
- mysql修改字符集位utf-8使其和操作数据库连接字符程序统一
- excel
- 程序开发的验证工作
- iOS 支付宝集成
- Centos修炼----->centos7办公环境打造(No1--桌面快捷方式创建)
- WebService
- ubuntu系统下Elasticsearch 安装
- 无重复数字的三位数(第0届第3题)