力扣_二叉树卡片题目答案汇总
题目来源
这里只是附上各个代码答案,并不做解释,至少现在不做解释。
代码
二叉树类
from collections import deque
# 数的节点类
class TreeNode(object):
def __init__(self, item):
self.val = item
self.left = None
self.right = None
# python 二叉树类
class Tree(object):
def __init__(self):
self.root = None
self.res = 0
def construct_tree(self, values=None):
if not values:
return None
self.root = TreeNode(values[0])
queue = deque([self.root])
leng = len(values)
nums = 1
while nums < leng:
node = queue.popleft()
if node:
node.left = TreeNode(values[nums]) if values[nums] else None
queue.append(node.left)
if nums + 1 < leng:
node.right = TreeNode(values[nums + 1]) if values[nums + 1] else None
queue.append(node.right)
nums += 1
nums += 1
def bfs(self):
res = []
queue = deque([self.root])
while queue:
node = quque.popleft()
if node:
res.append(node.val)
queue.append(node.left)
queue.append(node.right)
return ret
# 迭代遍历,数据存储一层一个列表
# if not root:
# return []
# queue = deque([self.root])
# ret = []
# while queue:
# list_1 = []
# for i in range(len(queue)):
# node = queue.popleft()
# if node.left:
# queue.append(node.left)
# if node.right:
# queue.append(node.right)
# list_1.append(node.val)
# ret.append(list_1)
# return ret
def pre_traversal(self):
ret = []
# 递归方式
# def traversal(head):
# if not head:
# return
# ret.append(head.val)
# traversal(head.left)
# traversal(head.right)
# traversal(self.root)
# 迭代方式
if not root:
return []
stack = [self.root]
while stack:
node = stack.pop()
ret.append(node.val)
if node.right: # 先加右子节点,因为列表pop先抛却最右的,
stack.append(node.right)
if node.left:
stack.append(node.left)
return ret
def in_traversal(self):
# 递归方式
# ret = []
# def traversal(head):
# if not head:
# return
# traversal(head.left)
# ret.append(head.val)
# traversal(head.right)
# traversal(self.root)
# 迭代方式
if not root:
return []
ret = []
stack = []
root = self.root
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
ret.append(root.val)
root = root.right
return ret
def pre_traversal(self):
# 递归方式
# ret = []
# def traversal(head):
# if not head:
# return
# traversal(head.left)
# traversal(head.right)
# ret.append(head.val)
# traversal(self.root)
# return ret
# 迭代方式
if not root:
return []
stack = [self.root]
ret = []
while stack:
node = stack.pop()
ret.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return result[::-1]
def get_depth(self, node):
# 自底向上
if not node:
return 0
return max(self.get_depth(node.left) + 1,
self.get_depth(node.right) + 1)
# 自顶向下
def get_depth2(self, node, depth):
if not node:
return
print(f"res===>{self.res}, depth===>{depth}")
if not node.left and not node.right:
self.res = max(self.res, depth)
depth += 1
self.get_depth2(node.left, depth)
self.get_depth2(node.right, depth)
return self.res
问题1 二叉树的最大深度
class Solution:
def maxDepth(self, root):
# 方法一:自底向上
if not root:
return 0
return max(self.maxDepth(root.left) + 1, self.maxDepth(root.right) + 1)
问题2 对称二叉树
from collections import deque
class Solution:
def isSymmetric(self, root):
# 方法一:递归
if not root:
return True
return self.isST(root.left, root.right)
def isST(self, left, right):
if not left and not right:
return True
if not left or not right or left.val != right.val:
return False
return self.isST(left.left, right.right) and self.isST(left.right, right.left)
问题3 路径总和
class Solution:
def hasPathSum(self, root, Pathsum):
# 方法一:DFS
if not root:
return False
if not root.left and not root.right:
return sum == root.val
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
问题4 从中序遍历和后序遍历构造二叉树
class Solution:
def buildTree(self, inorder, postorder):
if not inorder or not postorder:
return None
root = TreeNode(postorder[-1]) # 根节点
index = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:index], postorder[:index])
root.right = self.buildTree(inorder[index + 1:], postorder[index:-1])
return root
问题5 从前序与中序遍历序列构造二叉树
class Solution:
def buildTree(self, preorder, inorder):
if not preorder or not inorder:
return None
root = TreeNode(preorder[0])
index = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1: 1 + index], inorder[:index])
root.right = self.buildTree(preorder[index + 1:], inorder[index+1:])
return root
问题6 填充每个节点到下一个右侧节点指针
class Solution:
def connect(self, root): # root: 'Node' -> 'Node'
# 递归版:
if not root or not root.left:
return root
root.left.next = root.right
if root.next and root.right:
root.right.next = root.next.left
self.connect(root.left)
self.connect(root.right)
return root
# 迭代版
if not root:
return
the_root = root
while root.left is not None:
next_layer = root.left
while root.next is not None:
root.left.next = root.right
root.right.next = root.next.left
root = root.next
root.left.next = root.right
root = next_layer
return the_root
问题7 填充每个节点的下一个右侧节点指针II
class Solution:
def connect(self, root): # root: 'Node' -> 'Node'
# 迭代版
head = root
while head:
cur = head
pre = head = None
while cur:
if cur.left:
if not pre:
pre = head = cur.left
else:
pre.next = cur.left
pre = pre.next
if cur.right:
if not pre:
pre = head = cur.right
else:
pre.next = cur.right
pre = pre.next
cur = cur.next
return root
问题8 二叉树的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root, p, q): # root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if root is None:
return None
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right: # p q 分别在左右两子树中
return root
if not left: # p q 都在右子树中
return right
if not right: # p q 都在左子树中
return left
问题9 二叉树的序列化与反序列化
from collections import deque
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
s = ""
stack = [root]
while stack:
root = stack.pop(0)
if root:
s += str(root.val)
stack.append(root.left)
stack.append(root.right)
else:
s += "n"
s += " "
return s
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
tree = data.split()
if tree[0] == "n":
return None
stack = []
root = TreeNode(int(tree[0]))
stack.append(root)
i = 1
while stack:
cur = stack.pop(0)
if cur == None:
continue
cur.left = TreeNode(int(tree[i])) if tree[i] != "n" else None
cur.right = TreeNode(int(tree[i + 1])) if tree[i + 1] != "n" else None
i += 2
stack.append(cur.left)
stack.append(cur.right)
return root