寻找两个有序数组的中位数
可参考88.合并两个有序数组
对称二叉树
import io
import sys
class TreeNode:
def __init__(self,val=0,left=None,right=None):
self.val=val
self.left=left
self.right=right
def stringToTreeNode(input):
input=input.strip() #去掉[]
input=input[1:-1]
if not input:
return None
inputValues=[s.strip() for s in input.split(',')] #记得加中括号
root=TreeNode(int(inputValues[0]))
nodeQueue=[root] #声明一个list表示队列,并且内部存储结构是二叉树
front=0
index=1
while index<len(inputValues):
node=nodeQueue[front] #声明构造一个nodeQueue队头,用于之后引导node.left和node.right等左右孩子结点
front=front+1 #前继结点
item_left=inputValues[index]
index=index+1
if item_left!="null":
leftNumber=int(item_left) #注意:需先强转成integer
node.left=TreeNode(leftNumber) #注意调用的是TreeNode类用(),不是中括号
nodeQueue.append(node.left)
if index>=len(inputValues):
break
item_right = inputValues[index]
index = index + 1
if item_right!="null":
rightNumber = int(item_right) # 注意:需先强转成integer
node.right = TreeNode(rightNumber)
nodeQueue.append(node.right)
return root
class Solution:
def isSymmetrical(self, root:TreeNode):
if not root:
return None
def DFS(left,right):
if not (left or right): #注意
return True
if not (left and right):
return False
if left.val!=right.val:
return True
return DFS(left.left, right.right) and DFS(left.right,right.left)
return DFS(root.left,root.right)
def EnterMain():
def readlines():
for lines in io.TextIOWrapper(sys.stdin.buffer,encoding='utf-8'):
yield lines.strip('\n')
lines=readlines()
while True:
try:
line=next(lines)
node=stringToTreeNode(line)
result=Solution().isSymmetrical(node)
out=str(result)
print(out)
except StopIteration:
break
if __name__ == '__main__':
EnterMain()
二叉树的层平均值
import io
import json
import sys
"""
#元组形式(值和下标一一对应)
#要注意判空
"""
def stringToIntegerList(input):
return json.loads(input)
class TreeNode:
def __init__(self,val=0,left=None,right=None):
self.val=val
self.left=left
self.right=right
def stringToTreeNode(input):
input=input.strip() #用于去除首位的字符,不写则为去除首尾的空格(如果有空格的话)
input=input[1:-1]
if not input:
return None
inputValues=[s.strip() for s in input.strip(',')] #注意这个中括号,此时传入[values]中括号到inputValues数组里面,之后index需要从1开始取值
root=TreeNode(int(inputValues[0])) #初始化
nodeQueue=[root] #声明构造一个list表示队列,所以root外面有个中括号,这个root类似一个哑结点,以便最后通过它返回所有的值
front=0
index=1
while index<len(inputValues):
node=nodeQueue[front] #有了之前的nodeQueue=[root],这里才好生成对头
front=front+1
item_left=inputValues[index]
index=index+1
if item_left != "null":
leftNumber=int(item_left) #注意判空,因为这个有些是没有结点的
node.left=TreeNode(leftNumber)
nodeQueue.append(node.left)
if index>=len(inputValues):#注意这里的防止溢出判断放在while里面
break
item_right=inputValues[index]
index=index+1 #这里还是用到了的,注意return root 在while外面
if item_right != "null":
rightNumber=int(item_left)
node.right=TreeNode(rightNumber)
nodeQueue.append(node.right)
return root
class Solution:
def averageOflevels(self,root:TreeNode):
numbersSum=list()
count=list()
def DFS(root:TreeNode,level:int):
if not root:
return
if level<len(numbersSum):
numbersSum[level]=root.val #下标,一个val涵盖一层所有左右子结点
count[level]+=1
else:
numbersSum.append(root)
count.append(1)
DFS(root.left,level+1)
DFS(root.right,level+1)
DFS(root,0) #从根结点,值和下标开始
return [numbersSum/count for numbersSum,count in zip(numbersSum,count)]
def EnterMain():
def readlines():
for line in io.TextIOWrapper(sys.stdin.buffer,encoding='utf-8'):
yield line.strip('\n')
lines=readlines()
while True:
try:
line=next(lines)
LN=stringToTreeNode(line)
result=Solution().averageOflevels(LN)
out=str(result)
print(out)
except StopIteration:
break
if __name__ == '__main__':
EnterMain()
字典树(前缀树)
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
self.end = "#"
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for char in word:
node = node.setdefault(char, {})
node[self.end] = None
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return self.end in node
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for s in prefix:
if s in node.keys():
node = node[s]
else:
return False
return True
前序+后序->层次遍历
import io
import json
import sys
from typing import List
def stringToIntegerList(input):
return json.loads(input)
class TreeNode:
def __init__(self,val=0,left=None,right=None):
self.val=val
self.left=left
self.right=right
class Solution: #注意这里不要有括号
def constructFromPrePost(self,pre: List[int],post:List[int]):
if not pre:
return None
root = TreeNode(pre[0])
if len(pre)==1:
return root
L=post.index(pre[1])+1
root.left =self.constructFromPrePost(pre[1:L+1],post[:L])
root.right=self.constructFromPrePost(pre[L+1:],post[L:-2])
return root #记得返回根结点带动递归
def TreeNodeToString(root): #利用队列
if not root:
return '[]'
output=""
current=0
Queue=[root]
while current != len(Queue):
node=Queue[current]
current+=1
if not node:
output += "null, "
continue
output+=str(node.val)+", " #注意这里是node.val
Queue.append(node.left)
Queue.append(node.right)
return "["+output[:-2]+"]"
def EnterMain():
def readlines():
for lines in io.TextIOWrapper(sys.stdin.buffer,encoding='utf-8'):
yield lines.strip('\n')
lines=readlines()
while True:
try:
line = next(lines)
pre = stringToIntegerList(line)
line = next(lines)
post= stringToIntegerList(line)
TN=Solution().constructFromPrePost(pre,post)
result=TreeNodeToString(TN)
print(result)
except StopIteration:
break
if __name__ == '__main__':
EnterMain()