39.平衡二叉树
问题:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解决:
思想:
平衡二叉树指的是,左右子树的高度差不大于1的树(包含空树)。
python代码:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
if(pRoot==None):
return True
if(abs(self.deep(pRoot.left)-self.deep(pRoot.right))>1):
return False
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
def deep(self,node):
if(node==None):
return 0
nleft=self.deep(node.left)
nright=self.deep(node.right)
return max(nleft+1,nright+1)


122

被折叠的 条评论
为什么被折叠?



