剑指Offer 54 二叉搜索树的第k大节点

二叉搜索树的第k大节点

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

 1 # -*- coding:utf-8 -*-
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 class Solution:
 8     def __init__(self):
 9         self.l = []
10         self.count = 0
11         
12     def inOrder(self,root,k):
13         if root != None:
14             self.inOrder(root.left,k)
15             self.count += 1
16             if self.count == k:
17                 self.l.append(root)
18             self.inOrder(root.right,k)
19         
20     # 返回对应节点TreeNode
21     def KthNode(self, pRoot, k):
22         if k == 0:
23             return None
24         self.inOrder(pRoot,k)
25         if k > self.count:
26             return None
27         return self.l[0]
28         # write code here
原文地址:https://www.cnblogs.com/asenyang/p/11016230.html