题目描述:
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
题目来源:牛客网
代码实现(python2)
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
flag = 0
def KthNode(self, pRoot, k):
# write code here
node_list = []
def middle_sort(pRoot,k):
if not pRoot:
return
middle_sort(pRoot.left,k)
node_list.append(pRoot)
self.flag += 1
if self.flag == k:
return
middle_sort(pRoot.right,k)
middle_sort(pRoot,k)
return node_list[k-1] if 0<k<=len(node_list) else None
题目解析
二叉搜索树(BST:Binary Search Tree),又称二叉查找树。是一种特殊的二叉树,它改善了二叉树节点查找的效率。二叉查找树有以下性质:
对于任意一个节点 n,
其左子树(left subtree)下的每个后代节点(descendant node)的值都小于节点 n 的值;
其右子树(right subtree)下的每个后代节点的值都大于节点 n 的值。
根据二叉搜索树的性质可以得出:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。
所以只要中序遍历二叉搜索树,返回第k个结点即可。
代码中做了一个小优化,引入flag,即当找到第k个结点时,停止遍历,不再进行后续遍历过程。