看到一个有意思的题目,二叉树(搜索树)验证(判断)。用python实现。
首先,搜索树/查找树/排序树(Binary Sort Tree)定义:所有树节点都有左结点<根节点<右节点。即:1).所有左子树节点都小于根节点,根节点小于所有右结点。2).左右子树又同样定义。
(一).先用最简单的思想递归来实现,容易写出并理解,但在效率上有些折扣,当数据体量较大时,复杂度的限制就容易体现出来。话不多说,上代码:
class Node(object): #递归算法
def __init__(self,data,left=0,right=0):
self.data=data
self.left=left
self.right=right
def charge(self):
if not self:
return True
if (self.left==None) and (self.right==None): #左右分支均无
return True
if self.left==None: #仅有右分支
if self.data<self.right.data:
r = self.right
while r.left: #找到右子树的最左子节点
r = r.left
if self.data>=r.data:
return False
return self.right.charge()
else:
return False
if self.right==None: #仅有左分支
if self.left.data<self.data:
l = self.left
while l.right: #左子树的最右结点
l = l.right
if l.data >= self.data:
return False
return self.left.charge()
else:
return False
#左右分支均有
if self.left.data<self.data and self.data<self.right.data:
l = self.left
while l.right:
l = l.right
if l.data>=self.data:
return False
r = self.right
while r.left:
r = r.left
if self.data>=r.data:
return False
return (self.left.charge() and self.right.charge())
else:
return False
if __name__ == ‘__main__’:
# 手动创建一课二叉树
print(‘手动创建一课二叉树’)
tree = Node(1)
tree.left = Node(2, None, None)
tree.right = Node(3, None, None)
tree.left.left = Node(4, None, None)
tree.left.right = Node(5, None, None)
tree.right.left = Node(6, None, None)
tree.right.right = Node(7, None, None)
tree.left.left.left = Node(8, None, None)
tree.left.left.right = Node(9, None, None)
tree.left.right.left = Node(10, None, None)
tree.left.right.left = Node(11, None, None)
print(“手动创建一颗二叉(搜索)树并判断”)
print(tree.charge())
#再创建一个搜索树
print(“创建一个二叉(搜索)树并判断”)
tree0 = Node(8)
tree0.left = Node(5, None, None)
tree0.right = Node(10, None, None)
tree0.left.left = Node(3, None, None)
tree0.left.right = Node(6, None, None)
tree0.right.left = Node(9, None, None)
tree0.right.right = Node(11, None, None)
tree0.left.left.left = Node(2, None, None)
tree0.left.left.right = Node(4, None, None)
print(tree0.charge())
可见,基本的实现及判断都没问题。或者还有其它的写法实现,欢迎讨论!
另外,基于队列的宽度优先遍历的方法复杂度会小一些(O(n)),下一篇单独介绍。
可以转载,但请注明出处!