LeeCode解题:判断二叉树是否平衡

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值