【发布时间】:2017-07-14 20:35:22
【问题描述】:
class BTNode:
"""Binary Tree node."""
def __init__(self: ’BTNode’, data: object,
left: ’BTNode’=None, right: ’BTNode’=None) -> None:
"""Create BT node with data and children left and right."""
self.data, self.left, self.right = data, left, right
def is_bst(t: BTNode) -> bool:
if not t:
return False
if not t.left and not t.right:
return True
if t.left and t.right:
if not(t.data > t.left.data) or not(t.data < t.right.data):
return False
else:
return is_bst(t.left) and is_bst(t.right)
函数描述说,如果以 t 为根的二叉树具有 BST 属性,则返回 True。
is_bst(BTNode(8, BTNode(9, BTNode(2, None, None), BTNode(6, None, None)),\
BTNode(10, None, None)))
以下调用在应该返回 False 时返回 True,因为左分支中的 9 大于根值 8。这违反了 BST 属性
我不确定为什么会得到这个输出。你能告诉我我的功能有什么问题吗?
谢谢
【问题讨论】:
标签: python-3.x binary-search-tree