正所谓人生苦短,我用 Python , 下面使用 Python 实现 先序遍历 和 后序遍历 ,代码也是相当简洁
树结构
下面以这颗树的结构为例:
1
/|\
2 3 4
/\
5 6
具体代码
import networkx as nx
import matplotlib.pyplot as plt
class Node:
def __init__(self, val:int) -> None:
self.val = val
self.children = []
pass
class Solution:
def preorder(self, root: Node)->list[int]:
"""
先序遍历
"""
def dfs(root, ans):
if not root: return
ans.append(root.val)
for child in root.children:
dfs(child, ans)
ans:list[int] = []
dfs(root, ans)
return ans
def postorder(self, root: Node)->list[int]:
"""
后序遍历
"""
def dfs(root, ans):
if not root: return
for child in root.children:
dfs(child, ans)
ans.append(root.val)
ans:list[int] = []
dfs(root, ans)
return ans
# 构建树结构为
# 1
# /|\
# 2 3 4
# /\
# 5 6
root = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node6 = Node(6)
root.children.append(node2)
root.children.append(node3)
root.children.append(node4)
node3.children.append(node5)
node3.children.append(node6)
print("先序遍历")
print(Solution().preorder(root=root))
print("后序遍历")
print(Solution().postorder(root=root))