阅读目录
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路及Python实现
- 如下图的二叉搜索树,因为二叉搜索树如果中序遍历的话,它是有序的,那么第k小的结点,就是第k个结点,所以只需要中序遍历即可!
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
ret = []
def in_order(root):
if root is None:
return None
in_order(root.left)
ret.append(root)
in_order(root.right)
in_order(pRoot)
if len(ret) < k or k < 1:
return None
else:
return ret[k - 1]