leetcode112 路径总和
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
return self.traversal(root, targetSum - root.val)
def traversal(self, cur: TreeNode, count: int):
if not cur.left and not cur.right and count == 0:
return True
if not cur.left and not cur.right:
return False
if cur.left:
count -= cur.left.val
if self.traversal(cur.left, count):
return True
count += cur.left.val
if cur.right:
count -= cur.right.val
if self.traversal(cur.right, count):
return True
count += cur.right.val
return False
leetcode106 从中序与后序遍历序列构造二叉树
从本题和下面的这两道题学习如何根据中序和前序、中序和后序遍历序列构造二叉树。同时,没有中序的情况是不能构造二叉树的
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)
seperator_idx = inorder.index(root_val)
inorder_left = inorder[:seperator_idx]
inorder_right = inorder[seperator_idx + 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
leetcode115 从前序与中序遍历序列构造二叉树
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)
seperator_idx = inorder.index(root_val)
inorder_left = inorder[:seperator_idx]
inorder_right = inorder[seperator_idx + 1:]
preorder_left = preorder[1:1 + len(inorder_left)]
preorder_right = preorder[1 + len(inorder_left):]
root.left = self.buildTree(preorder_left, inorder_left)
root.right = self.buildTree(preorder_right, inorder_right)
return root