LeeCode 100
解题思路:
可借用AVL树的构造思想,引入平衡因子,如果节点有右子节点,节点平衡因子减一,有左子节点,加一。假若最后根节点值大于1或者小于-1,则该二叉树不平衡。
#建立二叉树
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
self.balanceFactor =0 # 平衡因子
def insertLeft(self,newNode):
if isinstance(newNode,BinaryTree):
t = newNode
else:
t = BinaryTree(newNode)
if self.leftChild is not None:
t.leftChild = self.leftChild
t.balanceFactor +=1
else:
self.leftChild = t
t.balanceFactor +=1
def insertRight(self,newNode):
if isinstance(newNode,BinaryTree):
t = newNode
else:
t = BinaryTree(newNode)
if self.rightChild is not None:
t.rightChild = self.rightChild
t.balanceFactor -=1
else:
self.rightChild = t
t.balanceFactor -=1
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def getRootVal(self):
return self.key
def getBalanceFactor(self):
return self.balanceFactor
def inorder(self):
if self.leftChild:
self.leftChild.inorder()
if self.key is not None:
print(self.key)
print(self.balanceFactor)
if self.rightChild:
self.rightChild.inorder()
#中序遍历二叉树
def inorder(tree):
if tree != None:
inorder(tree.getLeftChild())
print(tree.getRootVal())
print('the balance factor is {}'.format(tree.getBalanceFactor()))
inorder(tree.getRightChild())
#插入数据
right_tree = BinaryTree(20)
right_tree.leftChild = BinaryTree(15)
right_tree.rigthChild = BinaryTree(7)
left_tree = BinaryTree(9)
tree = BinaryTree(3)
tree.leftChild =left_tree
tree.rigthChild = right_tree
inorder(tree)
#输出结果
9
the balance factor is 0
3
the balance factor is 0