打卡Day16
- 1.513. 找树左下角的值
- 2.112. 路径总和
- 扩展
- 113. 路径总和 II
- 3.106.从中序与后序遍历序列构造二叉树
- 扩展
- 105. 从前序与中序遍历序列构造二叉树
- 从前序与后序遍历序列构造二叉树?
1.513. 找树左下角的值
题目链接:513. 找树左下角的值
文档讲解: 代码随想录
递归法:
class Solution(object):def findBottomLeftValue(self, root):""":type root: TreeNode:rtype: int"""self.res = None #不可以为0self.max_depth = float('-inf')self.traversal(root, 1)return self.resdef traversal(self, node, depth):if not node.left and not node.right:if depth > self.max_depth:self.max_depth = depthself.res = node.valreturnif node.left:self.traversal(node.left, depth + 1)#回溯#depth += 1#self.traversal(node.left, depth)#depth -= 1if node.right:self.traversal(node.right, depth + 1)
迭代法:
class Solution(object):def findBottomLeftValue(self, root):""":type root: TreeNode:rtype: int"""queue = collections.deque([root])levels = []while queue:level = []size = len(queue)for i in range(size): node = queue.popleft()level.append(node.val)if node.left:queue.append(node.left)if node.right:queue.append(node.right)levels.append(level)return levels[-1][0]
class Solution(object):def findBottomLeftValue(self, root):""":type root: TreeNode:rtype: int"""queue = collections.deque([root])res = 0while queue:size = len(queue)for i in range(size): node = queue.popleft()if i == 0:#我没想到res = node.valif node.left:queue.append(node.left)if node.right:queue.append(node.right)return res
2.112. 路径总和
题目链接:112. 路径总和
文档讲解: 代码随想录
class Solution(object):def hasPathSum(self, root, targetSum):""":type root: TreeNode:type targetSum: int:rtype: bool"""if not root:return Falsereturn self.traversal(root, targetSum - root.val)def traversal(self, node, count):if not node.left and not node.right and count == 0:return Trueif not node.left and not node.right:return Falseif node.left:count -= node.left.valif self.traversal(node.left, count):return Truecount += node.left.valif node.right:count -= node.right.valif self.traversal(node.right, count):return Truecount += node.right.valreturn False
精简版
class Solution(object):def hasPathSum(self, root, targetSum):""":type root: TreeNode:type targetSum: int:rtype: bool"""if not root:return Falseif not root.left and not root.right and targetSum == root.val:return Truereturn self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)
迭代法
class Solution(object):def hasPathSum(self, root, targetSum):""":type root: TreeNode:type targetSum: int:rtype: bool"""if not root:return Falsestack = [(root, root.val)]while stack:node, path_sum = stack.pop()if not node.left and not node.right and path_sum == targetSum:return Trueif node.right:stack.append((node.right, path_sum + node.right.val))if node.left:stack.append((node.left, path_sum + node.left.val))return False
扩展
113. 路径总和 II
题目链接:113
class Solution(object):def __init__(self):self.res = []self.path = []def pathSum(self, root, targetSum):""":type root: TreeNode:type targetSum: int:rtype: List[List[int]]"""if not root:return []self.path.append(root.val)self.traversal(root, targetSum - root.val)return self.resdef traversal(self, node, count):if not node.left and not node.right and count == 0:self.res.append(self.path[:])returnif not node.left and not node.right:returnif node.left:#要先把左子树的值保存self.path.append(node.left.val)count -= node.left.valself.traversal(node.left, count)count += node.left.val#路径也要回溯self.path.pop()if node.right:self.path.append(node.right.val)count -= node.right.valself.traversal(node.right, count)count += node.right.valself.path.pop()return
class Solution(object):def pathSum(self, root, targetSum):""":type root: TreeNode:type targetSum: int:rtype: List[List[int]]"""res = []if not root:return resself.traversal(root, targetSum, [], res)return resdef traversal(self, node, count, path, res):if not node:returnpath.append(node.val)count -= node.valif not node.left and not node.right and count == 0:res.append(list(path))self.traversal(node.left, count, path, res)self.traversal(node.right, count, path, res)path.pop()
迭代法
class Solution(object):def pathSum(self, root, targetSum):""":type root: TreeNode:type targetSum: int:rtype: List[List[int]]"""if not root:return []res = []stack = [(root, [root.val])] #元组的第二个元素的类型为list,方便求和while stack:node, path = stack.pop()if not node.left and not node.right and sum(path) == targetSum:res.append(path)if node.right:stack.append((node.right, path + [node.right.val]))if node.left:stack.append((node.left, path + [node.left.val]))return res
3.106.从中序与后序遍历序列构造二叉树
题目链接:106.从中序与后序遍历序列构造二叉树
文档讲解: 代码随想录
class Solution(object):def buildTree(self, inorder, postorder):""":type inorder: List[int]:type postorder: List[int]:rtype: TreeNode"""#判断树是否为空if not postorder:return None#后序遍历的最后一个当前的中间节点root_val = postorder[-1]root = TreeNode(root_val)#找切割点separator_index = inorder.index(root_val)#切割中序数组,得到前序数组的左右半边inorder_left = inorder[:separator_index]inorder_right = inorder[separator_index + 1:]#切割后序数组,得到后序数组的左右两边#中序数组的大小一定要和后序数组大小一样postorder_left = postorder[: len(inorder_left)]postorder_right = postorder[len(inorder_left):len(postorder) - 1]#递归root.left = self.buildTree(inorder_left, postorder_left)root.right = self.buildTree(inorder_right, postorder_right)return root
扩展
105. 从前序与中序遍历序列构造二叉树
题目链接:105
class Solution(object):def buildTree(self, preorder, inorder):""":type preorder: List[int]:type inorder: List[int]:rtype: TreeNode"""#终止条件if not preorder:return None#得到中间节点root_val = preorder[0]root = TreeNode(root_val)#找到切割点separator_index = inorder.index(root_val)#切割inorder_left = inorder[:separator_index]inorder_right = inorder[separator_index + 1:]preorder_left = preorder[1:len(inorder_left) + 1] #注意这里切割的终点要加1,因为是从preorder[1]开始的preorder_right = preorder[len(inorder_left) + 1:len(preorder)]#递归root.left = self.buildTree(preorder_left, inorder_left)root.right = self.buildTree(preorder_right, inorder_right)return root
从前序与后序遍历序列构造二叉树?
不可以,因为无法确定中间节点在哪里,不能唯一确定一棵二叉树。