目录
1.226. 翻转二叉树 - 力扣(LeetCode) (leetcode-cn.com)
2.101. 对称二叉树 - 力扣(LeetCode) (leetcode-cn.com)
3.100. 相同的树 - 力扣(LeetCode) (leetcode-cn.com)
4.572. 另一棵树的子树 - 力扣(LeetCode) (leetcode-cn.com)
5.104. 二叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)
6.559. N 叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)
7.111. 二叉树的最小深度 - 力扣(LeetCode) (leetcode-cn.com)
8.222. 完全二叉树的节点个数 - 力扣(LeetCode) (leetcode-cn.com)
9.110. 平衡二叉树 - 力扣(LeetCode) (leetcode-cn.com)
10.257. 二叉树的所有路径 - 力扣(LeetCode) (leetcode-cn.com)
11.404. 左叶子之和 - 力扣(LeetCode) (leetcode-cn.com)
12.513. 找树左下角的值 - 力扣(LeetCode) (leetcode-cn.com)
13.112. 路径总和 - 力扣(LeetCode) (leetcode-cn.com)
14.113. 路径总和 II - 力扣(LeetCode) (leetcode-cn.com)
15.106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)
16.105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)
17.654. 最大二叉树 - 力扣(LeetCode) (leetcode-cn.com)
18.617. 合并二叉树 - 力扣(LeetCode) (leetcode-cn.com)
1.226. 翻转二叉树 - 力扣(LeetCode) (leetcode-cn.com)
(1)递归写法
# 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 invertTree(self, root: TreeNode) -> TreeNode:
if root==None:
return None
root.left,root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
(2)迭代之深度优先
# 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 invertTree(self, root: TreeNode) -> TreeNode:
if root==None:
return None
stack=[root]
while stack:
top=stack.pop()
top.left,top.right=top.right,top.left
if top.left:
stack.append(top.left)
if top.right:
stack.append(top.right)
return root
(3)迭代之广度优先
# 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 invertTree(self, root: TreeNode) -> TreeNode:
if root==None:
return None
from collections import deque
que=deque([root])
while que:
top=que.popleft()
top.left,top.right=top.right,top.left
if top.left:
que.append(top.left)
if top.right:
que.append(top.right)
return root
2.101. 对称二叉树 - 力扣(LeetCode) (leetcode-cn.com)
(1)递归
# 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 isSymmetric(self, root: TreeNode) -> bool:
return self.compare(root.left,root.right)
def compare(self,left,right):
if left==None and right==None:return True
if left==None and right!=None:return False
if left!=None and right==None:return False
elif left.val!=right.val:return False
x=self.compare(left.left,right.right)
y=self.compare(left.right,right.left)
return x and y
(2)迭代
# 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 isSymmetric(self, root: TreeNode) -> bool:
from collections import deque
que=deque([])
que.append(root.right)
que.append(root.left)
while que:
leftnode=que.popleft()
rightnode=que.popleft()
if leftnode==None and rightnode==None:
continue
if not leftnode or not rightnode or leftnode.val != rightnode.val:
return False
que.append(leftnode.left)
que.append(rightnode.right)
que.append(leftnode.right)
que.append(rightnode.left)
return True
3.100. 相同的树 - 力扣(LeetCode) (leetcode-cn.com)
(1)递归
# 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 isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
return self.compare(p,q)
def compare(self,x,y):
if x==None and y==None:
return True
if not x or not y or x.val!=y.val:
return False
a=self.compare(x.left,y.left)
b=self.compare(x.right,y.right)
return a and b
(2)迭代法
# 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 isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
from collections import deque
que=deque([])
que.append(q)
que.append(p)
while que:
x=que.popleft()
y=que.popleft()
if x==None and y==None:
continue
if not x or not y or x.val!=y.val:
return False
que.append(x.left)
que.append(y.left)
que.append(x.right)
que.append(y.right)
return True
4.572. 另一棵树的子树 - 力扣(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 isSubtree(self, root: TreeNode, subRoot: TreeNode) -> bool:
if root==None:
return False
result1=self.compare(root,subRoot)
result2=self.isSubtree(root.left,subRoot)
result3=self.isSubtree(root.right,subRoot)
return result1 or result2 or result3
def compare(self,x,y):
if x==None and y==None:
return True
if not x or not y or x.val!=y.val:
return False
a=self.compare(x.left,y.left)
b=self.compare(x.right,y.right)
return a and b
5.104. 二叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)
(1)后序遍历(通过高度求深度)
# 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 maxDepth(self, root: Optional[TreeNode]) -> int:
return self.getheight(root)
def getheight(self,root):
if root==None:
return 0
lefth=self.getheight(root.left)
righth=self.getheight(root.right)
return max(lefth,righth)+1
(2)先序遍历(回溯法)(直接求深度)
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
result=0
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root==None:
return result
self.getheight(root,1)
return result
def getheight(self,root,height):
global result
result=max(result,height)
if root.left==None and root.right==None:
return
if root.left:
self.getheight(root.left,height+1)
if root.right:
self.getheight(root.right,height+1)
return
(3)层序遍历
# 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
result=0
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root==None:
return 0
from collections import deque
que=deque([root])
ans=0
while que:
ans+=1
size=len(que)
for i in range(size):
top=que.popleft()
if top.left:
que.append(top.left)
if top.right:
que.append(top.right)
return ans
6.559. N 叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if root==None:
return 0
depth=0
for i in root.children:
depth=max(depth,self.maxDepth(i))
depth+=1
return depth
7.111. 二叉树的最小深度 - 力扣(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 minDepth(self, root: TreeNode) -> int:
if root==None:
return 0
if root.left==None and root.right!=None:
return self.minDepth(root.right)+1
if root.left!=None and root.right==None:
return self.minDepth(root.left)+1
return 1+min(self.minDepth(root.left),self.minDepth(root.right))
8.222. 完全二叉树的节点个数 - 力扣(LeetCode) (leetcode-cn.com)
(1)前序遍历
# 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 countNodes(self, root: TreeNode) -> int:
return self.getnum(root)
def getnum(self,root):
if root==None:
return 0
return 1+self.getnum(root.left)+self.getnum(root.right)
(2)完全二叉树的性质
# 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 countNodes(self, root: TreeNode) -> int:
if root==None:
return 0
left=root.left
right=root.right
leftnum=0
rightnum=0
while(left):
left=left.left
leftnum+=1
while(right):
right=right.right
rightnum+=1
if leftnum==rightnum:
return (2**(leftnum+1))-1
return 1+self.countNodes(root.left)+self.countNodes(root.right)
9.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:
a=self.getheight(root)
if a==-1:
return False
return True
def getheight(self,root):
if root==None:
return 0
leftn=self.getheight(root.left)
rightn=self.getheight(root.right)
if leftn==-1:
return -1
if rightn==-1:
return -1
if abs(leftn-rightn)>1:
return -1
else:
return 1+max(leftn,rightn)
10.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]:
result=[]
path=[]
if root==None:
return result
self.traversal(root,result,path)
return result
def traversal(self,cur,result,path):
cur.val=str(cur.val)
path.append(cur.val)
if not cur.left and not cur.right:
ans="->".join(path)
result.append(ans)
return
if cur.left:
self.traversal(cur.left,result,path)
path.pop()
if cur.right:
self.traversal(cur.right,result,path)
path.pop()
11.404. 左叶子之和 - 力扣(LeetCode) (leetcode-cn.com)
(1)后序遍历
通过父节点来判断左节点是否为叶节点
# 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:
if root==None:
return 0
leftsum=self.sumOfLeftLeaves(root.left)
rightsum=self.sumOfLeftLeaves(root.right)
midsum=0
if root.left and not root.left.left and not root.left.right:
midsum=root.left.val
return midsum+leftsum+rightsum
(2)层序遍历
# 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:
if root==None:
return 0
stack=[]
stack.append(root)
ans=0
while stack:
top=stack.pop()
if top.left and not top.left.left and not top.left.right:
ans+=top.left.val
if top.left:
stack.append(top.left)
if top.right:
stack.append(top.right)
return ans
12.513. 找树左下角的值 - 力扣(LeetCode) (leetcode-cn.com)
(1)前序遍历
# 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:
maxlen=-1
leftvalue=0
def traversal(root,depth):
nonlocal maxlen,leftvalue
if root.left==None and root.right==None:
if depth>maxlen:
maxlen=depth
leftvalue=root.val
return
if root.left:
traversal(root.left,depth+1)
if root.right:
traversal(root.right,depth+1)
return
traversal(root,0)
return leftvalue
13.112. 路径总和 - 力扣(LeetCode) (leetcode-cn.com)
(1)深度优先搜索
# 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:
if root==None:
return False
def dfs(root,sums):
sums+=root.val
if root.left==None and root.right==None:
if sums==targetSum:
return True
return False
if root.left:
if dfs(root.left,sums):return True
if root.right:
if dfs(root.right,sums):return True
return False
return dfs(root,0)
14.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]]:
result=[]
if root==None:
return result
def dfs(root,sums,path):
nonlocal result
sums+=root.val
if root.left==None and root.right==None:
if sums==targetSum:
result.append(path+[root.val])
return
if root.left:
dfs(root.left,sums,path+[root.val])
if root.right:
dfs(root.right,sums,path+[root.val])
dfs(root,0,[])
return result
15.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:
if not postorder:
return None
rootnode=postorder[-1]
root=TreeNode(rootnode)
cut=inorder.index(rootnode)
inlefttree=inorder[:cut]
inrighttree=inorder[cut+1:]
postlefttree=postorder[:len(inlefttree)]
postrighttree=postorder[len(inlefttree):-1]
root.left=self.buildTree(inlefttree,postlefttree)
root.right=self.buildTree(inrighttree,postrighttree)
return root
16.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
rootnode=preorder[0]
cut=inorder.index(rootnode)
leftinorder=inorder[:cut]
rightinorder=inorder[cut+1:]
leftpreorder=preorder[1:1+len(leftinorder)]
rightpreorder=preorder[1+len(leftinorder):]
root=TreeNode(rootnode)
root.left=self.buildTree(leftpreorder,leftinorder)
root.right=self.buildTree(rightpreorder,rightinorder)
return root
17.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
rootvalue=max(nums)
index=nums.index(rootvalue)
root=TreeNode(rootvalue)
root.left=self.constructMaximumBinaryTree(nums[:index])
root.right=self.constructMaximumBinaryTree(nums[index+1:])
return root
18.617. 合并二叉树 - 力扣(LeetCode) (leetcode-cn.com)
(1)递归
# 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:
return root2
if 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
(2)迭代写法
# 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:
return root2
if not root2:
return root1
from collections import deque
que=deque([])
que.append(root1)
que.append(root2)
while que:
node1=que.popleft()
node2=que.popleft()
if node1.left and node2.left:
que.append(node1.left)
que.append(node2.left)
if node1.right and node2.right:
que.append(node1.right)
que.append(node2.right)
node1.val+=node2.val
if not node1.left and node2.left:
node1.left=node2.left
if not node1.right and node2.right:
node1.right=node2.right
return root1
# 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:
return root2
if not root2:
return root1
from collections import deque
que=[]
que.append(root2)
que.append(root1)
while que:
node1=que.pop()
node2=que.pop()
if node1.left and node2.left:
que.append(node2.left)
que.append(node1.left)
if node1.right and node2.right:
que.append(node2.right)
que.append(node1.right)
node1.val+=node2.val
if not node1.left and node2.left:
node1.left=node2.left
if not node1.right and node2.right:
node1.right=node2.right
return root1