day 18: 二叉树
Leetcode 513. Find Bottom Left Tree Value
Problem is find the first element if the bottom layer
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
# record first element of last layer:
queue = [root]
while queue:
l = len(queue)
for i in range(l):
node = queue.pop(0)
if i == 0 : res = node.val
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return res
BFS!!! YYDS!!!
Leetcode 112.Path Sum
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetsum: int) -> bool:
if not root:
return False
stack = [] # [(当前节点,路径数值), ...]
stack.append((root, root.val))
while stack:
cur_node, path_sum = stack.pop()
if not cur_node.left and not cur_node.right and path_sum == targetsum:
return True
if cur_node.right:
stack.append((cur_node.right, path_sum + cur_node.right.val))
if cur_node.left:
stack.append((cur_node.left, path_sum + cur_node.left.val))
return False
把每个节点和该节点的求和状态存储入栈! Nice!
Leetcode 106.Construct Binary Tree from Inorder and Postorder Traversal
好难 会思路也写不出来啊
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
# 第一步: 特殊情况讨论: 树为空. (递归终止条件)
if not postorder:
return None
# 第二步: 后序遍历的最后一个就是当前的中间节点.
root_val = postorder[-1]
root = TreeNode(root_val)
# 第三步: 找切割点.
separator_idx = inorder.index(root_val)
# 第四步: 切割inorder数组. 得到inorder数组的左,右半边.
inorder_left = inorder[:separator_idx]
inorder_right = inorder[separator_idx + 1:]
# 第五步: 切割postorder数组. 得到postorder数组的左,右半边.
# ⭐️ 重点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