做题记录
递归遍历、迭代遍历(栈)
class Solution(object):
def preorderTraversal(self, root):
res=[]
self.travel(res,root)
return res
def travel(self,res,root):
if root==None:return None
res.append(root.val)
self.travel(res,root.left)
self.travel(res,root.right)
class Solution(object):
def inorderTraversal(self, root):
res=[]
self.travel(res,root)
return res
def travel(self,res,root):
if root==None:return None
self.travel(res,root.left)
res.append(root.val)
self.travel(res,root.right)
class Solution(object):
def postorderTraversal(self, root):
res=[]
self.travel(res,root)
return res
def travel(self,res,root):
if root==None:return None
self.travel(res,root.left)
self.travel(res,root.right)
res.append(root.val)
class Solution(object):
def invertTree(self, root):
self.travel(root)
return root
def travel(self,root):
if not root:return None
root.left,root.right=root.right,root.left
self.travel(root.left)
self.travel(root.right)
层序遍历(使用队列实现)
class Solution(object):
def levelOrder(self, root):
from collections import deque
res=[]
if not root:return res
que=deque([root])
while que:
size=len(que)
result=[]
for i in range(size):
cur=que.popleft()
result.append(cur.val)
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
res.append(result)
return res
class Solution(object):
def rightSideView(self, root):
from collections import deque
res=[]
if not root:return res
que=deque([root])
while que:
tmp=que.pop()
res.append(tmp.val)
que.append(tmp)
size=len(que)
for i in range(size):
cur=que.popleft()
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
return res
class Solution(object):
def levelOrder(self, root):
results=[]
if not root:
return results
from collections import deque
que=deque([root])
while que:
size=len(que)
result=[]
for _ in range(size):
node=que.popleft()
result.append(node.val)
if node.children:
que.extend(node.children)
results.append(result)
return results
class Solution:
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
from collections import deque
res=[]
if not root:return res
que=deque([root])
while que:
size=len(que)
sum_=0
for i in range(size):
cur=que.popleft()
sum_+=cur.val
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
res.append(sum_/size)
return res
class Solution(object):
def largestValues(self, root):
res=[]
if not root:return res
from collections import deque
que=deque([root])
while que:
size=len(que)
max_=float('-inf')
for i in range(size):
cur=que.popleft()
if cur.val>max_:max_=cur.val
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
res.append(max_)
return res
class Solution(object):
def connect(self, root):
if not root:return None
que=[root]
while que:
size=len(que)
for i in range(size):
cur=que.pop(0)
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
if i==size-1:break
cur.next=que[0]
return root
完全二叉树只有两种情况,情况一:就是满二叉树(左右子树深度一致则为满二叉树),情况二:最后一层叶子节点没有满。
对于情况一,可以直接用 2^树深度 - 1 来计算,注意这里根节点深度为1。
对于情况二,分别递归左孩子,和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后依然可以按照情况1来计算。
class Solution(object):
def countNodes(self, root):
if not root:return 0
left=root.left
right=root.right
ld,rd=0,0
while left:
left=left.left
ld+=1
while right:
right=right.right
rd+=1
if rd==ld:
return (2<<ld)-1
return self.countNodes(root.left)+self.countNodes(root.right)+1
比较的是两个子树的里侧和外侧的元素是否相等。后序遍历
class Solution(object):
def isSymmetric(self, root):
return self.compare(root.left,root.right)
def compare(self,left,right):
if left and not right:return False
elif not left and right:return False
elif not left and not right:return True
elif left.val!=right.val:return False
ous=self.compare(left.left,right.right)
ins=self.compare(left.right,right.left)
return ous and ins
class Solution(object):
def isSameTree(self, p, q):
return self.compare(p,q)
def compare(self,p,q):
if not p and q:return False
elif p and not q :return False
elif not p and not q:return True
elif p.val!=q.val:return False
right=self.compare(p.right,q.right)
left=self.compare(p.left,q.left)
return right and left
class Solution(object):
def isSubtree(self, root, subRoot):
if not root and not subRoot:
return True
if not root or not subRoot:
return False
return self.sametree(root,subRoot) or self.isSubtree(root.left,subRoot) or self.isSubtree(root.right,subRoot)
def sametree(self,r,s):
if not r and not s:
return True
if not r or not s:
return False
return r.val==s.val and self.sametree(r.left,s.left) and self.sametree(r.right,s.right)
平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数。
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数。
求深度可以从上到下去查 所以需要前序遍历(中左右),而高度只能从下到上去查,所以只能后序遍历(左右中)
class Solution(object):
def isBalanced(self, root):
if self.getdepth(root)!=-1:return True
else:return False
def getdepth(self,root):
if not root:return 0
left=self.getdepth(root.left)
right=self.getdepth(root.right)
if left==-1:return -1
if right==-1:return -1
if abs(left-right)>1:return -1
else:return 1+max(left,right)
求二叉树深度
层序遍历,记录层数
class Solution(object):
def maxDepth(self, root):
if not root:return 0
from collections import deque
que=deque([root])
count=0
while que:
size=len(que)
count+=1
for _ in range(size):
cur=que.popleft()
if cur.left:que.append(cur.left)
if cur.right:que.append(cur.right)
return count
有左无右,return 1+左深度;有右无左,return 1+右深度。
class Solution(object):
def minDepth(self, root):
return self.getdepth(root)
def getdepth(self,root):
if not root:return 0
ld=self.getdepth(root.left)
rd=self.getdepth(root.right)
if root.left and not root.right:
return 1+ld
if not root.left and root.right:
return 1+rd
res=1+min(ld,rd)
return res
递归+回溯
class Solution(object):
def binaryTreePaths(self, root):
path=''
res=[]
self.travel(root,path,res)
return res
def travel(self,root,path,res):
path+=str(root.val)
if not root.left and not root.right:#叶子节点
res.append(path)#就将当前数据加入res
if root.left:
self.travel(root.left,path+'->',res)#若回溯,path不变
if root.right:
self.travel(root.right,path+'->',res)
层序遍历,判断左节点是否为叶子节点
class Solution(object):
def sumOfLeftLeaves(self, root):
if not root:return 0
from collections import deque
que=deque([root])
sum_=0
while que:
size=len(que)
for _ in range(size):
cur=que.popleft()
if cur.left:
que.append(cur.left)
if not cur.left.left and not cur.left.right:
sum_+=cur.left.val
if cur.right:
que.append(cur.right)
return sum_
每层记录第一个节点
class Solution(object):
def findBottomLeftValue(self, root):
if not root:return 0
from collections import deque
que=deque([root])
l=0
while que:
size=len(que)
l=que[0].val
for _ in range(size):
cur=que.popleft()
if cur.left:que.append(cur.left)
if cur.right:que.append(cur.right)
return l
判断叶子节点时,count是否为0。
class Solution(object):
def hasPathSum(self, root, targetSum):
if not root:return False
return self.travel(root,targetSum-root.val)
def travel(self,root,count):
if not root.left and not root.right and count==0:return True
if not root.left and not root.right:return False
if root.left:
if self.travel(root.left,count-root.left.val):
return True
if root.right:
if self.travel(root.right,count-root.right.val):
return True
return False
class Solution(object):
def pathSum(self, root, targetSum):
if not root:return None
self.path=[root.val]
self.res=[]
self.travel(root,targetSum-root.val)
return self.res
def travel(self,root,sum_):
if not root.left and not root.right and sum_==0:
self.res.append(self.path[:])
return
if not root.left and not root.right:return
if root.left:
self.path.append(root.left.val)
sum_-=root.left.val
self.travel(root.left,sum_)
self.path.pop()
sum_+=root.left.val
if root.right:
self.path.append(root.right.val)
sum_-=root.right.val
self.travel(root.right,sum_)
self.path.pop()
sum_+=root.right.val
return
class Solution(object):
def buildTree(self, inorder, postorder):
if not inorder or not postorder:return None
root_val=postorder[-1]
root=TreeNode(root_val)
ind=inorder.index(root_val)
li=inorder[:ind]
ri=inorder[ind+1:]
lp=postorder[:len(li)]
rp=postorder[len(li):-1]
root.left=self.buildTree(li,lp)
root.right=self.buildTree(ri,rp)
return root
class Solution(object):
def buildTree(self, preorder, inorder):
if not preorder or not inorder:return None
root_val=preorder[0]
root=TreeNode(root_val)
ind=inorder.index(root_val)
li=inorder[:ind]
ri=inorder[ind+1:]
lp=preorder[1:1+len(li)]
rp=preorder[1+len(li):]
root.left=self.buildTree(lp,li)
root.right=self.buildTree(rp,ri)
return root
先找到数组中最大值构建为根节点,以其划分左右子树,递归生成左右子树
class Solution(object):
def constructMaximumBinaryTree(self, nums):
if not nums:return None
max_=max(nums)
ind=nums.index(max_)
root=TreeNode(max_)
l=nums[:ind]
r=nums[ind+1:]
root.left=self.constructMaximumBinaryTree(l)
root.right=self.constructMaximumBinaryTree(r)
return root
class Solution(object):
def mergeTrees(self, root1, root2):
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