在 Python 中實現樹資料結構

Sahil Bhosale 2023年10月10日

1. 父節點：具有一個或多個子節點的節點。
2. 子節點：具有父節點的節點。
3. 葉子節點：沒有任何子節點的節點。

在 Python 中從頭開實現樹資料結構

``````class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
``````

``````root = Node(10)

root.left = Node(34)
root.right = Node(89)
root.left.left = Node(45)
root.left.right = Node(50)
``````

``````          10
/    \
34      89
/    \
45    50
``````

在 Python 中遍歷二叉樹

前序遍歷

``````def preorder(node):
if node:
print(node.data)
preorder(node.left)
preorder(node.right)
``````

``````10
34
45
50
89
``````

中序遍歷

``````def inorder(node):
if node:
inorder(node.left)
print(node.data)
inorder(node.right)
``````

``````45
34
50
10
89
``````

後序遍歷

``````def postorder(node):
if node:
postorder(node.left)
postorder(node.right)
print(node.data)
``````

``````45
50
34
89
10
``````

使用 Python 庫實現樹

``````pip install anytree
``````

``````from anytree import Node, RenderTree

root = Node(10)

level_1_child_1 = Node(34, parent=root)
level_1_child_2 = Node(89, parent=root)
level_2_child_1 = Node(45, parent=level_1_child_1)
level_2_child_2 = Node(50, parent=level_1_child_2)

for pre, fill, node in RenderTree(root):
print("%s%s" % (pre, node.name))

# Tree Structure
#          10
#        /    \
#       34      89
#     /    \
#    45    50
``````

``````10
├── 34
│   └── 45
└── 89
└── 50
``````

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.