题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

  1. # -*- coding:utf-8 -*-
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. def IsBalanced_Solution(self, pRoot):
  9. # write code here
  10. if not pRoot:
  11. return True
  12. left_depth = self.get_depth(pRoot.left)
  13. right_depth = self.get_depth(pRoot.right)
  14. return abs(left_depth-right_depth)<=1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
  15. def get_depth(self, pRoot):
  16. if not pRoot:
  17. return 0
  18. return max(self.get_depth(pRoot.left),self.get_depth(pRoot.right))+1