二叉搜索树的第k个节点--python版

题目描述

给定一棵二叉搜索树,请找出其中的第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     # 返回对应节点TreeNode
 9     def KthNode(self, pRoot, k):
10         # write code here
11         # 按照中序遍历
12         result = []
13         if not pRoot:
14             return None
15         result = self.mid(pRoot,result)
16         if k>len(result) or k<=0:
17             return None
18         return result[k-1]
19     def mid(self,pRoot,result):
20         if pRoot:
21             self.mid(pRoot.left,result)
22             result.append(pRoot)
23             self.mid(pRoot.right,result)
24         return result
25         

note:

找节点

result.append(pRoot)

如果只找值,则

result.append(pRoot.val)

 

猜你喜欢

转载自www.cnblogs.com/shuangcao/p/13170038.html