剑指offer46 — 二叉搜索树的第k个结点
题目
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
分析
由于二叉搜索树的特殊性,中序遍历第k个结点即为从小到大的第k个数据。即写一个中序遍历的函数,调用并利用一个辅助数组进行遍历结果存储即可。
代码
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
retList = []
def preOrder(pRoot):
# 中序遍历
if pRoot == None:
return None
preOrder(pRoot.left)
retList.append(pRoot)
preOrder(pRoot.right)
preOrder(pRoot)
if len(retList) < k or k < 1:
return None
return retList[k-1]