当前位置:   article > 正文

代码随想录算法训练营第17天|二叉树(四)

代码随想录算法训练营第17天|二叉树(四)

题目链接:110. 平衡二叉树

思路:后序递归遍历左右子树,判断左右子树是否为平衡树,若左右子树高度差绝对值不超过1,则为平衡树

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution(object):
  8. def getHeight(self,node):
  9. if not node:
  10. return 0
  11. leftHeight=self.getHeight(node.left)
  12. if leftHeight==-1:return -1
  13. rightHeight=self.getHeight(node.right)
  14. if rightHeight==-1:return -1
  15. if abs(leftHeight-rightHeight)>1:
  16. return -1
  17. else:
  18. return max(leftHeight,rightHeight)+1
  19. def isBalanced(self, root):
  20. """
  21. :type root: TreeNode
  22. :rtype: bool
  23. """
  24. if self.getHeight(root)==-1:
  25. return False
  26. else:
  27. return True


题目链接:257. 二叉树的所有路径

思路:递归加回溯。

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution(object):
  8. def travelback(self,cur,path,result):
  9. path.append(cur.val)
  10. if cur.left is None and cur.right is None:
  11. spath='->'.join(map(str,path))
  12. result.append(spath)
  13. return
  14. if cur.left:
  15. self.travelback(cur.left,path,result)
  16. path.pop()
  17. if cur.right:
  18. self.travelback(cur.right,path,result)
  19. path.pop()
  20. def binaryTreePaths(self, root):
  21. """
  22. :type root: TreeNode
  23. :rtype: List[str]
  24. """
  25. path=[]
  26. result=[]
  27. if not root:
  28. return result
  29. self.travelback(root,path,result)
  30. return result


题目链接:404. 左叶子之和

思路:左叶子之和,左子树左叶子之和加右子树左叶子之和

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution(object):
  8. def sumOfLeftLeaves(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: int
  12. """
  13. if root is None:
  14. return 0
  15. if root.left is None and root.right is None:
  16. return 0
  17. leftValue=self.sumOfLeftLeaves(root.left)
  18. if root.left is not None and root.left.left is None and root.left.right is None:
  19. leftValue=root.left.val
  20. rightVaue=self.sumOfLeftLeaves(root.right)
  21. return leftValue+rightVaue

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/694901
推荐阅读
相关标签
  

闽ICP备14008679号