Python判断平衡二叉树

本文阅读 1 分钟
首页 Python笔记 正文

基于二叉树的深度,再次进行递归。以此判断左子树的高度和右子树的高度差是否大于1,若是则不平衡,反之平衡。

  1. '''
  2. 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
  3. '''
  4. # -*- coding:utf-8 -*-
  5. class TreeNode:
  6. def __init__(self, x):
  7. self.val = x
  8. self.left = None
  9. self.right = None
  10. class Solution:
  11. def __init__(self):
  12. self.flag = True
  13. def IsBalanced_Solution(self, pRoot):
  14. self.getDepth(pRoot)
  15. return self.flag
  16. def getDepth(self, pRoot):
  17. if pRoot == None:
  18. return 0
  19. left = 1 + self.getDepth(pRoot.left)
  20. right = 1 + self.getDepth(pRoot.right)
  21. if abs(left - right) > 1:
  22. self.flag = False
  23. return left if left > right else right
  24. class Solution2:
  25. def getDepth(self, pRoot):
  26. if pRoot == None:
  27. return 0
  28. return max(self.getDepth(pRoot.left), self.getDepth(pRoot.right)) + 1
  29. def IsBalanced_Solution(self, pRoot):
  30. if pRoot == None:
  31. return True
  32. if abs(self.getDepth(pRoot.left)-self.getDepth(pRoot.right)) > 1:
  33. return False
  34. return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
  35. pNode1 = TreeNode(1)
  36. pNode2 = TreeNode(2)
  37. pNode3 = TreeNode(3)
  38. pNode4 = TreeNode(4)
  39. pNode5 = TreeNode(5)
  40. pNode6 = TreeNode(6)
  41. pNode7 = TreeNode(7)
  42. pNode1.left = pNode2
  43. pNode1.right = pNode3
  44. pNode2.left = pNode4
  45. pNode2.right = pNode5
  46. pNode3.right = pNode6
  47. pNode5.left = pNode7
  48. S = Solution2()
  49. print(S.getDepth(pNode1))
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

Python二叉树的深度
« 上一篇 01-21
Python数组中只出现一次的数字
下一篇 » 01-21

发表评论

惪特博客
  • 文章总数:
    18498 篇
  • 评论总数:
    53266 条
  • 标签总数:
    8869 个
  • 总浏览量:
    21899602 次
  • 最后更新:
    2月27日

最多点赞

随便看看

标签TAG