Python二叉搜索树第k大的节点 Python实现查找二叉搜索树第k大的节点功能示例
hustfc 人气:0本文实例讲述了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程序设计有所帮助。
加载全部内容