LCR 045找树左下角的值
题目链接LCR 045. 找树左下角的值 - 力扣(LeetCode)
思路
我能不能用层序遍历,然后遍历到最后一层,把第一个数取出来
可以
提交

python
# 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
import collections
class Solution:
def findBottomLeftValue(self, root: TreeNode) -> int:
queue=collections.deque([root])
res=[]
while queue:
level=[]
for _ in range(len(queue)):
cur=queue.popleft()
level.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
res.append(level)
return res[-1][0]
需要注意的是queue里面保存的是节点,不是节点的值
112.路径总和
思路
之前做过寻找所有路径的题(257. 二叉树的所有路径),那这个在那个题的基础上求一下和,再判断一下就行了
在这个里面有介绍257.二叉树的所有路径的写法
提交

python
# 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 hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
res=[]
path=[]
if not root:
return False
self.traversal(root,path,res)
if targetSum in res:
return True
else:
return False
def traversal(self,cur,path,res):
path.append(cur.val)
if not cur.left and not cur.right:
spath=sum(path)
res.append(spath)
return
if cur.left:
self.traversal(cur.left,path,res)
path.pop()
if cur.right:
self.traversal(cur.right,path,res)
path.pop()
106.从中序与后序遍历序列构造二叉树
题目链接106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
思路
以前写过有点印象,记忆中比较复杂
先看一下理论知识,举一个例子

有点懂了,就是在后序里面找根,回到中序,分
割左右子树。
然后循环这个过程,直到找完
那代码怎么写,毫无思路
-
第一步:如果数组大小为零的话,说明是空节点了。
-
第二步:如果不为空,那么取后序数组最后一个元素作为节点元素。
-
第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
-
第四步:切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
-
第五步:切割后序数组,切成后序左数组和后序右数组
-
第六步:递归处理左区间和右区间
需要注意的就是切割,注意循环不变量的问题,就是处理的时候如果是左开右闭,那全部都是这个规则
用列表切片的方法,得到的是左闭右开类型

提交

python
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> 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数组的左,右半边.
# 重点: 中序数组大小一定跟后序数组大小是相同的.
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