先掌握递归法
110. 平衡二叉树
存在左右子树不平衡时,就标记
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
def traversal(root):
if not root:
return 0
else:
left = traversal(root.left)
right = traversal(root.right)
# check the balance
if abs(left-right) > 1:
# unbalanced
return -2
elif left == -2 or right == -2:
return -2
else:
height = max(left,right)
return height+1
404. 左叶子之和
慢慢一步步分析
考虑left 和 root.right.left的不同情况
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
left_left_leaves_sum = self.sumOfLeftLeaves(root.left) # 左
right_left_leaves_sum = self.sumOfLeftLeaves(root.right) # 右
cur_left_leaf_val = 0
if root.left and not root.left.left and not root.left.right:
cur_left_leaf_val = root.left.val
return cur_left_leaf_val + left_left_leaves_sum + right_left_leaves_sum # 中
257. 二叉树的所有路径
回溯思路
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
path = ""
res = []
cur = root
# def recursion(root,cur,path):
# if not root:
# print(path)
# if path not in res:
# res.append(path)
# return res
# if path == "":
# path = str(root.val)
# else:
# path = path + '->' + str(root.val)
# if not root.right and root.left:
# recursion(root.left,cur,path)
# elif not root.left and root.right:
# recursion(root.right,cur,path)
# else:
# recursion(root.left,cur,path)
# recursion(root.right,cur,path)
# # path = str(root.val)
def recursion(cur,path,res):
path += str(cur.val)
# 若当前节点为leave,直接输出
if not cur.left and not cur.right:
res.append(path)
if cur.left:
# + '->' 是隐藏回溯
recursion(cur.left, path + '->', res)
if cur.right:
recursion(cur.right, path + '->', res)
recursion(root,path,res)
return res