# 在 Python 中实现树数据结构

Sahil Bhosale 2024年2月15日

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.