Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. # 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
  2.  
  3. # class TreeNode:
  4. # def __init__(self, x):
  5. # self.val = x
  6. # self.left = None
  7. # self.right = None
  8.  
  9. class Solution:
  10. def IsBalanced_Solution(self, pRoot):
  11. return self.get_balanced_and_height(pRoot)[0]
  12.  
  13. def get_balanced_and_height(self, p):
  14. if p is None:
  15. return True, 0
  16. lb = self.get_balanced_and_height(p.left)
  17. rb = self.get_balanced_and_height(p.right)
  18. height = max(lb[1], rb[1]) + 1
  19. balanced = (-1 <= lb[1] - rb[1] <= 1)
  20. if lb[0] and rb[0]:
  21. return balanced, height
  22. else:
  23. return False, height
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement