python 二叉树总结(一)
二叉树前中后遍历(深度优先)
# 递归法
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def Traversal(root):
if root == None:
return
res.append(root.val)
Traversal(root.left)
Traversal(root.right)
Traversal(root)
return res
# 迭代法
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
# 递归法
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def Traversal(root):
if root == None:
return
Traversal(root.left)
Traversal(root.right)
res.append(root.val)
Traversal(root)
return res
# 迭代法
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root == None:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return res[::-1]
# 递归法
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def Traversal(root):
if root == None:
return
Traversal(root.left)
res.append(root.val)
Traversal(root.right)
Traversal(root)
return res
# 迭代法
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
stack = [] # 不能提前将root结点加入stack中
res = []
cur = root
while cur or stack:
# 先迭代访问最底层的左子树结点
if cur:
stack.append(cur)
cur = cur.left
# 到达最左结点后处理栈顶结点
else:
cur = stack.pop()
res.append(cur.val)
# 取栈顶元素右结点
cur = cur.right
return res
前中后迭代统一遍历法:
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
stack = []
res = []
if root:
stack.append(root)
while stack:
node = stack.pop()
if node != None:
stack.append(node)
stack.append(None)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
else:
node = stack.pop()
res.append(node.val)
return res
二叉树层序遍历(广度优先)
迭代法:
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if root == None:
return res
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.left:
que.append(node.left)
if node.right:
que.append(node.right)
res.append(result)
return res
递归法:
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
def helper(node, depth):
if node == None:
return []
if len(res) == depth:res.append([])
res[depth].append(node.val)
if node.left:
helper(node.left, depth + 1)
if node.right:
helper(node.right, depth + 1)
helper(root, 0)
return res
107.二叉树的层次遍历II
从下至上就是把result倒过来
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
if root == None:
return []
res = []
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.left:
que.append(node.left)
if node.right:
que.append(node.right)
res.append(result)
return res[::-1]
199.二叉树的右视图
res 里 保存每个result 的最后一位就行
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
res = []
if root == None:
return res
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.left:
que.append(node.left)
if node.right:
que.append(node.right)
res.append(result[-1])
return res
class Solution:
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
res = []
if root == None:
return res
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.left:
que.append(node.left)
if node.right:
que.append(node.right)
res.append(sum(result) / len(result))
return res
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
res = []
if root == None:
return res
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)
res.append(result)
return res
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
res = []
if root == None:
return res
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.left:
que.append(node.left)
if node.right:
que.append(node.right)
res.append(max(result))
return res
层序遍历法:
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
if root == None:
return None
from collections import deque
que = deque([root])
while que:
n = len(que)
for i in range(n):
node = que.popleft()
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
if i == n-1:
break
node.next = que[0]
return root
链表:
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
if not root:
return None
head = root
while head:
cur = head
while cur:
if cur.left: cur.left.next = cur.right
if cur.right and cur.next: cur.right.next = cur.next.left
cur = cur.next
head = head.left
return root
层序遍历:
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
from collections import deque
que = deque([root])
while que:
size = len(que)
for i in range(size):
node = que.popleft()
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
if i == size - 1:
break
node.next = que[0]
return root
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
res = []
from collections import deque
que = deque([root])
while que:
n = len(que)
result = []
for _ in range(n):
node = que.popleft()
result.append(node.val)
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
res.append(result)
return len(res)
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
from collections import deque
que = deque([(root, 1)])
while que:
size = len(que)
for _ in range(size):
node, depth = que.popleft()
if node.left == None and node.right == None:
return depth
if node.left:
que.append((node.left, depth + 1))
if node.right:
que.append((node.right, depth + 1))
return que[0][1]
翻转二叉树
层序遍历:
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
from collections import deque
que = deque([root])
while que:
size = len(que)
for _ in range(size):
node = que.popleft()
node.left, node.right = node.right, node.left
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
return root
递归(前序):
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
def inver(node):
if not node:
return
node.left, node.right = node.right, node.left
inver(node.left)
inver(node.right)
inver(root)
return root
迭代(前序):
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return root