Merge pull request #2759 from miaoxu404/master

Update 0513.找树左下角的值.md
This commit is contained in:
程序员Carl
2024-10-16 10:18:20 +08:00
committed by GitHub
2 changed files with 11 additions and 11 deletions

View File

@ -564,10 +564,10 @@ class Solution:
return False
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
return self.traversal(root, sum - root.val)
return self.traversal(root, targetSum - root.val)
```
(版本二) 递归 + 精简
@ -579,12 +579,12 @@ class Solution:
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
if not root.left and not root.right and sum == root.val:
if not root.left and not root.right and targetSum == root.val:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)
```
(版本三) 迭代
@ -596,7 +596,7 @@ class Solution:
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
# 此时栈里要放的是pair<节点指针,路径数值>
@ -659,13 +659,13 @@ class Solution:
return
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
self.result.clear()
self.path.clear()
if not root:
return self.result
self.path.append(root.val) # 把根节点放进路径
self.traversal(root, sum - root.val)
self.traversal(root, targetSum - root.val)
return self.result
```
@ -678,7 +678,7 @@ class Solution:
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
result = []
self.traversal(root, targetSum, [], result)
@ -703,7 +703,7 @@ class Solution:
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:
return []
stack = [(root, [root.val])]

View File

@ -55,7 +55,7 @@
参数必须有要遍历的树的根节点还有就是一个int型的变量用来记录最长深度。 这里就不需要返回值了所以递归函数的返回类型为void。
本题还需要类里的两个全局变量maxLen用来记录最大深度result记录最大深度最左节点的数值。
本题还需要类里的两个全局变量maxDepth用来记录最大深度result记录最大深度最左节点的数值。
代码如下: