class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res = []
def dfs(root, path):
if not root:
return
if not root.left and not root.right:
path.append(root.val)
res.append(path)
dfs(root.left, path + [root.val])
dfs(root.right, path + [root.val])
dfs(root, list())
print(res)
257. 二叉树的所有路径
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res = []
def dfs(root, path):
if not root:
return
if not root.left and not root.right:
path.append(root.val)
res.append(path)
dfs(root.left, path + [root.val])
dfs(root.right, path + [root.val])
dfs(root, list())
return ['->'.join([str(i) for i in re]) for re in res]
112. 路径总和
递归方法
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
if not root.left and not root.right and root.val == sum:
return True
sum -= root.val
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
dfs方法
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
res = []
def dfs(root, path):
if not root:
return
if not root.left and not root.right:
path.append(root.val)
res.append(path)
dfs(root.left, path + [root.val])
dfs(root.right, path + [root.val])
dfs(root, list())
ret = []
for i in res:
val = 0
for j in i:
val += j
if val == sum:
return True
return False
113. 路径总和 II
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res = []
def dfs(root, path):
if not root:
return
if not root.left and not root.right:
path.append(root.val)
res.append(path)
dfs(root.left, path + [root.val])
dfs(root.right, path + [root.val])
dfs(root, list())
ret = []
for i in res:
val = 0
for j in i:
val += j
if val == sum:
ret.append(i)
return ret
1022. 从根到叶的二进制数之和
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
res = []
def dfs(root, path):
if not root:
return
if not root.left and not root.right:
path.append(root.val)
res.append(path)
dfs(root.left, path + [root.val])
dfs(root.right, path + [root.val])
dfs(root, list())
val = [''.join([str(i) for i in re]) for re in res]
return (sum(int(i,2) for i in val))
129. 求根到叶子节点数字之和
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
res = []
def dfs(root, path):
if not root:
return
if not root.left and not root.right:
path.append(root.val)
res.append(path)
dfs(root.left, path + [root.val])
dfs(root.right, path + [root.val])
dfs(root, list())
val = [''.join([str(i) for i in re]) for re in res]
return (sum(int(i,10) for i in val))
543. 二叉树的直径
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
self.max_d = 0
def get_depth(root):
if not root:
return 0
left = get_depth(root.left)
right = get_depth(root.right)
self.max_d = max(self.max_d,left+right+1)
return max(left,right) + 1
get_depth(root)
return self.max_d - 1