513. 找树左下角的值
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
from collections import deque
_list = deque()
_list.append(root)
while(_list):
for i in range(len(_list)):
node = _list.popleft()
if i == 0:
result = node.val
if node.left:
_list.append(node.left)
if node.right:
_list.append(node.right)
return result
层序遍历一下,每次行开始的时候记录一下每行首位的值,遍历结束之后就是左下角的值
112. 路径总和
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def search_path(root, path, result):
if not root:
return
path = path + root.val
if not root.left and not root.right:
result.append(path)
return
if root.left:
search_path(root.left, path, result)
if root.right:
search_path(root.right, path, result)
return
path = 0
result = []
search_path(root, path, result)
return targetSum in result
定义一个search_path函数递归遍历 记录下每条路径的值为path, result中加入path的值,因为是通过子节点是否为空来返回,所以path的更新要放在最前面。
如果子节点为空,说明当前节点就是叶子节点了,那么return回去的时候,上一层的path并没有增加,所以不需要有退回的操作。换句话说叶子节点的值是在最后一层递归加上的,所以返回的时候path的值就是除了当前叶子节点的值。
105. 前序和中序构建二叉树
# 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 buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
#递归拆解成最小的子问题,就是构建一个头节点,头节点的left为左子树,right为右子树
#因为递归函数需要实现的就是具体怎么构建子树,所以左子树和右子树的实现用递归函数来完成,写的时候先默认它可以实现这个功能
#左右子树的构建就需要用到preorder前序和inorder中序的递归变化
if not inorder:
return
val = preorder[0] #前序遍历的头节点就是preorder[0]
cur = TreeNode(val = val) #建立头节点
left_inorder = inorder[:inorder.index(val)] #左子树的中序就是头节点把原来中序遍历分开的左边
right_inorder = inorder[inorder.index(val) + 1:] #右子树的中序就是头节点把原来中序遍历分开的右边
left_preorder = preorder[1:len(left_inorder) + 1] #左子树的前序就要用到左子树中序的长度来截出
right_preorder = preorder[len(left_inorder) + 1:] #右子树的前序同理
cur.left = self.buildTree(left_preorder, left_inorder) #递归实现左子树和右子树的构建 并和头节点连接
cur.right = self.buildTree(right_preorder, right_inorder)
return cur #返回头节点
106.中序后序构造二叉树
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not inorder:
return
cur_val = postorder[-1]
root = TreeNode(val = cur_val)
left_inorder = inorder[:inorder.index(cur_val)]
right_inorder = inorder[inorder.index(cur_val) + 1:]
left_postorder = postorder[:len(left_inorder)]
right_postorder = postorder[len(left_inorder): len(postorder) - 1]
root.left = self.buildTree(left_inorder, left_postorder)
root.right = self.buildTree(right_inorder, right_postorder)
return root
分成以下几个步骤:
1. 后序的最后一个节点取出来就是根节点
2. 用根节点去切中序,前半部分就是左子树 后半部分就是右子树
3. 在中序和后序分别取出左中序子树 右中序子树 左后序子树 右后序子树
4. 递归分别作为根节点的左子树去递归和右子树去递归