Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
kth-smallest-element-in-a-bst.py 1.01 KB
一键复制 编辑 原始数据 按行查看 历史
SangHee Kim 提交于 2019-01-14 01:46 +08:00 . add a solution (#30)
# Time: O(max(h, k))
# Space: O(h)
class Solution(object):
# @param {TreeNode} root
# @param {integer} k
# @return {integer}
def kthSmallest(self, root, k):
s, cur, rank = [], root, 0
while s or cur:
if cur:
s.append(cur)
cur = cur.left
else:
cur = s.pop()
rank += 1
if rank == k:
return cur.val
cur = cur.right
return float("-inf")
# time: O(max(h, k))
# space: O(h)
from itertools import islice
class Solution2(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
def gen_inorder(root):
if root:
for n in gen_inorder(root.left):
yield n
yield root.val
for n in gen_inorder(root.right):
yield n
return next(islice(gen_inorder(root), k-1, k))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助