110. 平衡二叉树 bool(-1)是True,另外要理解如何边计算高度边比较。引入result
# 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:
def get_height(root):
if root == None:
return 0
left_size = get_height(root.left)
if left_size ==-1:
return -1
right_size = get_height(root.right)
if right_size ==-1:
return -1
if abs(right_size - left_size) >1:
result =-1
else:
result = max(right_size,left_size)+1
return result
if get_height(root) != -1:
return True
else:
return False
257. 二叉树的所有路径 递归和回溯,用path记录路径
# 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]:
#使用前序遍历,用Path记录时要有回溯
def get_path(cur , path, result):
path.append(cur.val)
if cur.left ==None and cur.right == None:
result.append('->'.join(map(str, path)))
if cur.left:
get_path(cur.left,path,result)
path.pop()
if cur.right:
get_path(cur.right,path,result)
path.pop()
result=[]
get_path(root,[],result)
return result
# 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):
if root is None:
return 0
if root.left is None and root.right is None:
return 0
leftValue = self.sumOfLeftLeaves(root.left) # 左
if root.left and not root.left.left and not root.left.right: # 左子树是左叶子的情况
leftValue = root.left.val
rightValue = self.sumOfLeftLeaves(root.right) # 右
sum_val = leftValue + rightValue # 中
return sum_val