1.题目
给定一棵二叉搜索树,请找出其中的第k小的结点。例如,(5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为4。
2.思路
思路:如果是按中序遍历二叉搜索树的话,遍历的结果是递增排序的。所以只需要中序遍历就很容易找到第K个节点。
3.代码
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def __init__(self):
self.my_list = []
def in_order(self, pRoot):
if not pRoot:
return None
if pRoot.left:
self.in_order(pRoot.left)
self.my_list.append(pRoot)
if pRoot.right:
self.in_order(pRoot.right)
def KthNode(self, pRoot, k):
# write code here
self.in_order(pRoot)
if k <= 0 or k > len(self.my_list):
return None
return self.my_list[k - 1]