在Python中查找给定二叉树中是否存在BST的程序
假设我们有一棵二叉树。 我们必须找到树中最大的BST子树。我们将返回BST的根节点。
所以,如果输入如下:
那么输出将会是 –
为了解决这个问题,我们将采取以下步骤 –
- c:=0
- m:=空
- 定义一个函数recurse(),它将接受节点
- 如果节点不为空,则
- left_val:=recurse(节点的左侧)
- right_val:=recurse(节点的右侧)
- count:=负无穷大
- 如果(node.left为null或node.left.val<= node.val)和(右侧节点为null或node.val <= node.right.val),则
- count:= left_val + right_val + 1
- 如果计数> c,则
- c:= count
- m:= node
- 返回计数
- 返回0
- 如果节点不为空,则
- recurse(root)
- 返回m
例子
让我们看看以下实现,以获得更好的理解 –
class TreeNode:
def __init__(self, val, left = None, right = None):
self.val = val
self.left = left
self.right = right
def insert(temp,data):
que = []
que.append(temp)
while (len(que)):
temp = que[0]
que.pop(0)
if (not temp.left):
if data is not None:
temp.left = TreeNode(data)
else:
temp.left = TreeNode(0)
break
else:
que.append(temp.left)
if (not temp.right):
if data is not None:
temp.right = TreeNode(data)
else:
temp.right = TreeNode(0)
break
else:
que.append(temp.right)
def make_tree(elements):
Tree= TreeNode(elements[0])
for element in elements[1:]:
insert(Tree, element)
return Tree
def print_tree(root):
if root is not None:
print_tree(root.left)
print(root.val, end = ', ')
print_tree(root.right)
def solve(root):
c, m = 0, None
def recurse(node):
if node:
nonlocal c, m
left_val = recurse(node.left)
right_val = recurse(node.right)
count = -float("inf")
if (node.left == None or node.left.val <= node.val) and (node.right == None or node.val <= node.right.val):
count = left_val + right_val + 1
if count > c:
c = count
m = node
return count
return 0
recurse(root)
return m
tree = make_tree([1, 4, 6, 3, 5])
print_tree(solve(tree))
输入
tree = make_tree([1,4,6,3,5])
print_tree(solve(tree))
输出
3, 4, 5,