1.平衡二叉树
110. 平衡二叉树 - 力扣(LeetCode) (leetcode-cn.com)
# 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 isBalanced(self, root: TreeNode) -> bool:
def getHeight(noder):
if not noder :return 0
leftHeight = getHeight(noder.left) #左
if leftHeight==-1: return -1
rightHeight= getHeight(noder.right) #右
if rightHeight==-1: return-1
if abs(rightHeight-leftHeight)>1:result= -1 #中
else:result= 1+max(rightHeight,leftHeight)
return result
return bool(getHeight(root)+1)
2.递归法
257. 二叉树的所有路径 - 力扣(LeetCode) (leetcode-cn.com)
# 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 binaryTreePaths(self, root: TreeNode) -> List[str]:
res= []
def getPath(root,pathls):
if not root.left and not root.right:
res.append(pathls+str(root.val))
return
pathls+=str(root.val)+'->' #中
if root.left: getPath(root.left,pathls) #左
if root.right:getPath(root.right,pathls)#右
getPath(root,'')
return res
'''
#迭代法
class Solution:
"""二叉树的所有路径 迭代法"""
def binaryTreePaths(self, root: TreeNode) -> List[str]:
# 题目中节点数至少为1
stack, path_st, result = [root], [], []
path_st.append(str(root.val))
while stack:
cur = stack.pop()
path = path_st.pop()
# 如果当前节点为叶子节点,添加路径到结果中
if not cur.left and not cur.right: result.append(path)
if cur.right:
stack.append(cur.right) #无所谓左右 只要path_st能和stack对上就行
path_st.append(path + '->' + str(cur.right.val)) #
if cur.left:
stack.append(cur.left)
path_st.append(path + '->' + str(cur.left.val)) #
return result
513. 找树左下角的值 - 力扣(LeetCode) (leetcode-cn.com)
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
#递归法
maxDepth= -1
leftDepVal=0
def recur(root,depther):
nonlocal maxDepth, leftDepVal
if not root.left and not root.right:
if maxDepth< depther: #第一个出现的 比他大的 就是这层的最坐标
maxDepth = depther
leftDepVal= root.val
if root.left: recur(root.left, depther+1)
if root.right: recur(root.right,depther+1)
recur(root,0)
return leftDepVal
112. 路径总和 - 力扣(LeetCode) (leetcode-cn.com)
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def isornot(root,targetSum):
if not root: return False
targetSum-=root.val
if not root.left and not root.right and not targetSum: return True
return isornot(root.left,targetSum) or isornot(root.right,targetSum)
return isornot(root,targetSum)
113. 路径总和 II - 力扣(LeetCode) (leetcode-cn.com)
# 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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
#递归
res=[]
def rec(root,targetSum,pather):
if not root: return
targetSum-=root.val
pather.append(root.val)
if not root.left and not root.right and not targetSum:return res.append(pather)
if root.left: rec(root.left,targetSum,pather[:])
if root.right: rec(root.right,targetSum,pather[:])
pather.pop()
rec(root, targetSum, [])
return res
617. 合并二叉树 - 力扣(LeetCode) (leetcode-cn.com)
# 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 mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
#递归
if not root1 and not root2 :return None
elif not root1: return root2
elif not root2: return root1
root1.val+=root2.val
root1.left = self.mergeTrees(root1.left,root2.left)
root1.right= self.mergeTrees(root1.right,root2.right)
return root1
3.迭代法
404. 左叶子之和 - 力扣(LeetCode) (leetcode-cn.com)
# 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 sumOfLeftLeaves(self, root: TreeNode) -> int:
stack= [root]
res=0
while stack:
noder = stack.pop()
if not noder:
noder = stack.pop()
if not noder.left and not noder.right: res+=noder.val
if noder.left:
stack.append(noder.left)
stack.append(None)
if noder.right:stack.append(noder.right)
return res
513. 找树左下角的值 - 力扣(LeetCode) (leetcode-cn.com)
# 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 findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
#最好是层序遍历 最底层最左边的点 用迭代
queuer = deque([root])
res=0
while queuer:
for _ in range(len(queuer)):
noder = queuer.popleft()
if not _:res= noder.val #记录最后一行最左边数值
if noder.left: queuer.append(noder.left)
if noder.right:queuer.append(noder.right)
return res
112. 路径总和 - 力扣(LeetCode) (leetcode-cn.com)
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root: return False
#层序遍历
queue=deque([[root,targetSum]])
while queue:
for _ in range(len(queue)):
noder,pahtsum = queue.popleft()
pahtsum-=noder.val
if not noder.right and not noder.left and not pahtsum:return True
if noder.left:queue.append([noder.left,pahtsum])
if noder.right :queue.append([noder.right,pahtsum])
return False
617. 合并二叉树 - 力扣(LeetCode) (leetcode-cn.com)
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
if not root1:return root2
if not root2:return root1
#将两个同时放到队列里面比较
queue = deque([])
queue.append(root1)
queue.append(root2)
while queue:
noder1 = queue.popleft()
noder2 = queue.popleft()
noder1.val+= noder2.val
#如果两棵树左右节点都不为空,加入队列
if noder1.left and noder2.left:
queue.append(noder1.left)
queue.append(noder2.left)
if noder1.right and noder2.right:
queue.append(noder1.right)
queue.append(noder2.right)
#如果root1左或右为空 恰好root2 不为空
if not noder1.left and noder2.left: noder1.left = noder2.left
if not noder1.right and noder2.right: noder1.right = noder2.right
return root1
4.构造二叉树
106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)
中序:左中右
后序:左右中
注意中的位置 可以用以下办法
# 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, inorder: List[int], postorder: List[int]) -> TreeNode:
#用后序数组的最后一个 去切中序 前面为左边子节点 后面为右边子节点
#def sbuildtree(inorder: List[int], postorder: List[int]):
if not inorder:return None
root = TreeNode(postorder[-1])
inorindex = inorder.index(postorder[-1])
inorder_left= inorder[:inorindex] #必须用变量替换 重复选择 会
postindex= len(inorder_left)
root.left = self.buildTree(inorder_left,postorder[:postindex])
root.right= self.buildTree(inorder[inorindex+1:],postorder[postindex:-1])
return root
105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)
# 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]) -> TreeNode:
#前序 中左右 中序 左中右
#前序第一个为 根节点 然后用他去切割中序 ,反过来切割前序,分成左右支 继续递归
if not preorder:return None
root = TreeNode(preorder[0])
inoindex = inorder.index(preorder[0])
leftInorder = inorder[:inoindex]
preoindex = len(leftInorder)
root.left = self.buildTree(preorder[1:preoindex+1],leftInorder)
root.right= self.buildTree(preorder[preoindex+1:],inorder[inoindex+1:])
return root
654. 最大二叉树 - 力扣(LeetCode) (leetcode-cn.com)
# 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 constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
#找到最大值,然后左右分两边 继续递归
if not nums: return None
maxval = max(nums)
root = TreeNode(maxval)
index = nums.index(maxval)
root.left = self.constructMaximumBinaryTree(nums[:index])
root.right= self.constructMaximumBinaryTree(nums[index+1:])
return root
5.二叉搜索树
700. 二叉搜索树中的搜索 - 力扣(LeetCode) (leetcode-cn.com)
# 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 searchBST(self, root: TreeNode, val: int) -> TreeNode:
#层序搜索
queue = deque([root])
while queue:
noder = queue.popleft()
if noder.val== val: return noder
elif val> noder.val:
if noder.right:
queue.append(noder.right)
else:
if noder.left:
queue.append(noder.left)
return None
'''
'''
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
while root!=None:
if root.val> val : root= root.left
elif root.val<val: root= root.right
else:return root
return None
'''
class Solution:
#递归法
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:return None
if root.val>val:
return self.searchBST(root.left,val)
elif root.val<val:
return self.searchBST(root.right,val)
else:
return root
6.总结
明天还有二叉树的最后一天,应该可以看完,就剩下二叉搜索树了。