一、刷题:
1.leetcode题目 513 找树左下角的值(medium):
题目描述:513. 找树左下角的值 - 力扣(LeetCode)
解决:
迭代法:
# 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 findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
queue = collections.deque([root])
result = 0
while queue:
for i in range(len(queue)):
cur = queue.popleft()
if i == 0:
result = cur.val
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
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 findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
cur = 0
cur_h = 0
def dfs(node,height):
if not node:
return
height += 1
dfs(node.left,height)
dfs(node.right,height)
nonlocal cur,cur_h
if height>cur_h:
cur_h = height
cur = node.val
dfs(root,0)
return cur
2.leetcode 题目 112 路径总和(easy):
解决:
递归:(参数,终止条件、单层递归的逻辑)
# 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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
return targetSum == root.val
return self.hasPathSum(root.left,targetSum-root.val) or self.hasPathSum(root.right,targetSum-root.val)
3.leetcode 题目 113 路径总和II(medium):
题目描述:113. 路径总和 II - 力扣(LeetCode)
解决:
递归:
# 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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:
return []
path = []
result = []
def dfs(root,targetSum): ###确定参数
if not root:
return
path.append(root.val)
if not root.left and not root.right and targetSum == root.val: #确定终止条件
result.append(path[:])
dfs(root.left,targetSum-root.val) ###单层遍历的逻辑
dfs(root.right,targetSum-root.val)
path.pop() #回溯
dfs(root,targetSum)
return result