python

超轻量级php框架startmvc

Python实现查找二叉搜索树第k大的节点功能示例

更新时间:2020-06-22 11:42:01 作者:startmvc
本文实例讲述了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 二叉搜索树 第k大 节点