class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
que = collections.deque([root])
res = 0
while(que):
for i in range(len(que)):
cur = que.popleft()
if i == 0:
res = cur.val
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
return res
class Solution:
def get_sum(self, node, sum_, targetSum):
sum_ += node.val
if not node.left and not node.right:
return sum_ == targetSum
if node.left and self.get_sum(node.left, sum_, targetSum):
return True
if node.right and self.get_sum(node.right, sum_, targetSum):
return True
return False
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
return self.get_sum(root, 0, targetSum)
# 别人写的精简版
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
if not root.left and not root.right and targetSum == root.val:
return True
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)
我自己也写出来啦,但是这个精简版是真的牛。
class Solution:
def get_sum(self, node, path, cnt, res):
path.append(node.val)
cnt -= node.val
if not node.left and not node.right and cnt == 0:
res.append(path)
return res
if node.left:
res = self.get_sum(node.left, path[:], cnt, res)
if node.right:
res = self.get_sum(node.right, path[:], cnt, res)
return res
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:
return []
return self.get_sum(root, [], targetSum, [])
又是递归回溯,我又写出来啦
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_l = inorder[:separator_idx]
inorder_r = inorder[separator_idx + 1:]
# 分割后序数组
postorder_l = postorder[:len(inorder_l)]
postorder_r = postorder[len(inorder_l):len(postorder) - 1]
# 递归分割
root.left = self.buildTree(inorder_l, postorder_l)
root.right = self.buildTree(inorder_r, postorder_r)
return root
因为熟悉中序遍历和后序遍历,所以不会做,也不知道技巧,所以把代码抄了一遍。挺有意思的。
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if not preorder:
return None
# 获取中间节点
root_val = preorder[0]
root = TreeNode(root_val)
# 分割中序
separator_idx = inorder.index(root_val)
inorder_l = inorder[:separator_idx]
inorder_r = inorder[separator_idx + 1:]
# 分割前序
preorder_l = preorder[1: 1 + len(inorder_l)]
preorder_r = preorder[1 + len(inorder_l):]
root.left = self.buildTree(preorder_l, inorder_l)
root.right = self.buildTree(preorder_r, inorder_r)
return root
蛮有意思的,哈哈哈。
就是今天没有在十二点前做完,有点可惜。