什么是平衡二叉树:二叉树中所有节点中左右子树高度差不超过1
计算左右子树的高度差:用后序遍历:
计算左右子树高度,如果不满足平衡二叉树,则返回-1
如果左右子树都满足二叉树,则计算左右子树高度,如果还满足,则返回本轮计算的最大高度+1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if self.get_height(root) != -1:
return True
else:
return False
def get_height(self,node):
if not node:
return 0
left_height = self.get_height(node.left)
if left_height == -1:
return -1
right_height = self.get_height(node.right)
if right_height == -1:
return -1
if abs(left_height-right_height)>1:
return -1
else:
return 1+max(left_height,right_height)
257. 二叉树的所有路径 - 力扣(LeetCode)
回溯算法
解题关键:
迭代过程:
1、判断终止条件:到叶子结点终止,终止时收集
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
result = []
path=[]
if not root:
return result
self.traversal(root,path,result)
return result
def traversal(self,curr,path,result):
path.append(curr.val)
if not curr.left and not curr.right:
spath = "->".join(map(str,path))
result.append(spath)
if curr.left:
self.traversal(curr.left,path,result)
path.pop()
if curr.right:
self.traversal(curr.right,path,result)
path.pop()
404. 左叶子之和 - 力扣(LeetCode)s
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if not root.left and not root.right :
return 0
left_value = self.sumOfLeftLeaves(root.left)
if root.left and not root.left.left and not root.left.right:
left_value = root.left.val
right_value = self.sumOfLeftLeaves(root.right)
mid_value = left_value+right_value
return mid_value