您的位置:首页 > 其它

leetcode 之 Kth Smallest Element in a BST

2016-06-02 11:14 453 查看
题目描述:

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.

给定一棵二叉查找树, 找到第k个小的元素。

思路,利用二叉查找树的特性,其左子树的元素小于根节点,右子树的元素大于根节点。当采用中序遍历时,可以得到从小到大的排列。

因此采用中序遍历代码如下:

class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if not root:
return -1

res = []
ls = []
res.append(root)
while len(ls) != k:
while root.left:
root = root.left
res.append(root)
root = res.pop()
ls.append(root.val)
if root.right:
root = root.right
res.append(root)
return ls[-1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: