Python实现查找二叉搜索树第k大的节点功能示例
本文实例讲述了Python实现查找二叉搜索树第k大的节点功能。分享给大家供大家参考,具体如下:
题目描述
给定一个二叉搜索树,找出其中第k大的节点
就是一个中序遍历的过程,不需要额外的数组,便利到节点之后,k减一就行。
代码1
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.k = 0 def recursionKthNode(self, Root): result = None if result == None and Root.left: result = self.recursionKthNode(Root.left) if result == None: if self.k == 1: return Root self.k -= 1 if result == None and Root.right: result = self.recursionKthNode(Root.right) return result def KthNode(self, Root, k): if Root == None: return None self.k = k return self.recursionKthNode(Root) Root = TreeNode(5) Root.left = TreeNode(3) Root.left.left = TreeNode(2) Root.left.right = TreeNode(4) Root.right = TreeNode(7) Root.right.left = TreeNode(6) Root.right.right = TreeNode(8) print(Solution().KthNode(Root,3).val)
output : 4
代码2
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.k = 0 def InOrder(self, Root): ans = None if Root: if ans == None and Root.left: ans = self.InOrder(Root.left) #往左遍历 if ans == None and self.k == 1: ans = Root #遍历到目标节点 if ans == None and self.k != 1: #没有遍历到目标节点,k-- self.k -= 1 if ans == None and Root.right: #往右遍历 ans = self.InOrder(Root.right) return ans def KthNode(self, Root, k): if Root == None or k <= 0: return None self.k = k return self.InOrder(Root)
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
相关推荐
kikaylee 2020-11-11
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20