Tree structure
A tree (Tree) is anon-lineardata structure that models the branching hierarchy of trees in nature. Unlike linear structures such as arrays and linked lists, where elements follow one after another, the data elements in a tree (calledNode) have a clear one-to-many hierarchical relationship.
Tree structureJust like a real tree:
- Root Node: The root of the tree, the only node with no parent
- Child node: A node that branches out from another node
- Leaf Node: A node with no children, like a leaf
- Path: A route from one node to another
- Depth: The length of the path from the root to that node
- Height: The length of the path from that node to the farthest leaf
Analogies in daily life:
- Family tree: Grandparents → Parents → Children → Grandchildren
- Organizational structure: CEO → Director → Manager → Employee
- Filesystem: Root directory → Subdirectory → File
- Book classification: General category → Subcategory → Specific book
| Structure type | Search efficiency | Insertion efficiency | Deletion efficiency | Ordering |
|---|---|---|---|---|
| arrays | O(n) | O(n) | O(n) | None |
| Linked list | O(n) | O(1) | O(1) | None |
| Hash table | O(1) | O(1) | O(1) | None |
| Binary search tree | O(log n) | O(log n) | O(log n) | Yes |
Basic terminology
Before diving deeper, let's first familiarize ourselves with basic tree terminology:

- Node: Each element in a tree. It contains stored data and links to its child nodes.
- Root: The node at the top of the tree, the starting point of the whole tree. A tree has exactly one root node.
- Parent & Child: If node A connects to node B below it, then A is theParent nodeof B, and B is theChild nodeof A. A parent node can have multiple children.
- Siblings: Nodes that share the same parent are siblings of each other.
- Leaf: A node with no children, also called a terminal node.
- Edge: A line connecting two nodes, representing their relationship.
- Path: The sequence of nodes passed through from the root to a particular node.
- Height: The number ofedgeson the longest path from a node to its farthest leaf. The height of a tree is the height of its root.
- Depth: The number ofedgesedges on the path from the root to a node. The depth of the root is 0.
- Level: All nodes with the same depth belong to the same level. The root is at level 0.
Basic properties of trees
- Unique path: There is exactly one path between any two nodes in a tree.
- N nodes, N-1 edges: A tree with N nodes has a total of N-1 edges.
- Acyclic: There are no cycles in a tree (i.e., starting from a node and following edges, you can eventually return to it).
Why do we need trees? — Advantages and applications of trees
You might ask, with arrays and linked lists, why do we still need trees? The answer lies in efficiency.
- arrays: Fast lookup (by index), but slow insertion and deletion (requires moving many elements).
- Linked list: Fast insertion and deletion, but slow lookup (requires traversing from the head).
- Trees (especially binary search trees): While keeping data sorted, they provide much faster search than linked lists and more efficient insertion/deletion than arrays.
Practical Application Scenarios:
- Filesystem: Folders and files in a computer are organized in the form of a tree.
- Database index: B-trees and B+ trees are the core data structures for efficient database queries.
- Organizational charts: Hierarchical management of a company or department.
- Decision Tree: Classification models in artificial intelligence and machine learning.
- HTML DOM: The web page Document Object Model is a tree.
Binary Trees: The most important member of the tree family
A binary tree (Binary Tree) is a tree in which each node has at most two children, usually calledLeft child nodeandRight child node, and it is the foundation of many powerful tree structures (such as binary search trees, heaps, and AVL trees).
The basic structure is as follows:

Basic binary tree terminology
| Term | define | Life Analogy |
|---|---|---|
| Node | The basic unit containing data and pointers | A person in a family |
| Root Node | The top node of a tree | An ancestor in a family |
| Parent node | A node with children | Parent |
| Child node | A node pointed to by a parent | Child |
| Sibling node | Children of the same parent | Siblings |
| Leaf Node | A node with no children | A person with no children in a family |
| Depth | The number of edges from the root to that node | Generation number |
| Height | The number of edges from this node to the farthest leaf node | The number of generations the family continues |
Binary tree types
| Type | Feature | Time Complexity | Application scenarios |
|---|---|---|---|
| Ordinary binary tree | Each node has at most 2 children | O(n) | Expression tree |
| Full binary tree | Every node has either 0 or 2 children | O(n) | Huffman coding |
| Complete binary tree | Full except for the last level | O(n) | Heap implementation |
| Binary search tree | Left| Average O(log n) |
Search, sort |
|
| Balanced binary tree | The height difference between the left and right subtrees is at most 1 | O(log n) | Database index |
| Red-black trees | Colored balanced tree | O(log n) | Linux kernel |
Binary search tree operations
| Operation | Description | Time Complexity |
|---|---|---|
| Find | Find a node by value | Average O(log n), worst-case O(n) |
| insert | Insert a new node | Average O(log n), worst-case O(n) |
| Delete | Delete a specified node | Average O(log n), worst-case O(n) |
| Iteration | Visit all nodes | O(n) |
Binary tree traversal
Traversal refers to visiting every node in a tree according to some rule, with each node visited exactly once. This is the foundation of tree-related algorithms. There are four main ways:
-
Pre-order traversal (Pre-order):Root -> Left -> Right
-
In-order traversal (In-order):Left -> Root -> Right
-
Post-order traversal (Post-order):Left -> Right -> Root
-
Level-order traversal (Level-order):By level, from left to right

Example: For the binary tree shown below, the traversal results are as follows:
1
/ \
2 3
/ \ \
4 5 6
- Pre-order:1, 2, 4, 5, 3, 6
- In-order:4, 2, 5, 1, 3, 6
- Post-order:4, 5, 2, 6, 3, 1
- Level-order:1, 2, 3, 4, 5, 6
Practice: Implementing a Binary Tree in Python
Enough theory, let's get hands-on with code! We'll implement a simple binary tree node class and complete the insertion and traversal operations.
Step 1: Define the node class
Each node needs to store data and point to its left and right children.
Example
class
TreeNode:
"""Binary tree node class"""
def
init
(
self
,
value
)
:
self
.
value
=
value
The data stored in the node
self
.
left
=
None
Points to the left child
self
.
right
=
None
Points to the right child
def
str
(
self
)
:
"""Convenient for printing node information"""
return
f
"Node({self.value})"
Step 2: Build a sample tree
Let's manually build the tree from the example diagram earlier.
Example
Create nodes
root
=
TreeNode
(
1
)
node2
=
TreeNode
(
2
)
node3
=
TreeNode
(
3
)
node4
=
TreeNode
(
4
)
node5
=
TreeNode
(
5
)
node6
=
TreeNode
(
6
)
Build the connections (Links)
root.
left
=
node2
root.
right
=
node3
node2.
left
=
node4
node2.
right
=
node5
node3.
right
=
node6
(
f
"Root node: {root}"
)
(
f
"Left child of root node: {root.left}"
)
(
f
"Right child of root node: {root.right}"
)
Step 3: Implement traversal algorithms (recursive version)
Recursion is the most intuitive way to implement tree traversal.
Example
def
preorder_traversal
(
node
)
:
"""Pre-order traversal: Root -> Left -> Right"""
if
node
is
None
:
return
(
node.
value
,
end
=
' '
)
1. Visit the root node
preorder_traversal
(
node.
left
)
2. Traverse the left subtree
preorder_traversal
(
node.
right
)
3. Traverse the right subtree
def
inorder_traversal
(
node
)
:
"""In-order traversal: Left -> Root -> Right"""
if
node
is
None
:
return
inorder_traversal
(
node.
left
)
1. Traverse the left subtree
(
node.
value
,
end
=
' '
)
2. Visit the root node
inorder_traversal
(
node.
right
)
3. Traverse the right subtree
def
postorder_traversal
(
node
)
:
"""Post-order traversal: Left -> Right -> Root"""
if
node
is
None
:
return
postorder_traversal
(
node.
left
)
1. Traverse the left subtree
postorder_traversal
(
node.
right
)
2. Traverse the right subtree
(
node.
value
,
end
=
' '
)
3. Visit the root node
(
"\n--- Traversal Demo ---"
)
(
"Pre-order traversal result:"
,
end
=
' '
)
preorder_traversal
(
root
)
Output: 1 2 4 5 3 6
(
"\nIn-order traversal result:"
,
end
=
' '
)
inorder_traversal
(
root
)
Output: 4 2 5 1 3 6
(
"\nPost-order traversal result:"
,
end
=
' '
)
postorder_traversal
(
root
)
Output: 4 5 2 6 3 1
Step 4: Implement level-order traversal (using a queue)
Level-order traversal relies on the "first-in, first-out" property of a queue.
Example
from
collections
import
deque
def
level_order_traversal
(
root
)
:
"""Level-order traversal: Using a queue"""
if
root
is
None
:
return
queue
=
deque
(
[
root
]
)
Initialize the queue and put the root node in
while
queue:
current_node
=
queue.
popleft
(
)
1. Take a node from the left side of the queue
(
current_node.
value
,
end
=
' '
)
2. Visit that node
3. Add that node's children (if any) to the right side of the queue in order
if
current_node.
left
:
queue.
append
(
current_node.
left
)
if
current_node.
right
:
queue.
append
(
current_node.
right
)
(
"\nLevel-order traversal result:"
,
end
=
' '
)
level_order_traversal
(
root
)
Output: 1 2 3 4 5 6
Exercises and Challenges
Congratulations on completing the basics! To truly master trees, hands-on practice is essential.
Exercise 1: Calculate the height of a tree
Write a function tree_height(node)that takes the root node of a tree and returns the height of the tree (the height of an empty tree is -1 or 0, whichever convention you prefer; in this example we define it as the number of edges).
Tip: Tree height = 1 + max(height of the left subtree, height of the right subtree). This is a classic recursion problem.
Exercise 2: Search for a value in a binary tree
Write a function search_in_tree(node, target_value), search a given binary tree for whether there exists a node whose value equals target_value . If found, return True; otherwise, returns False。
Tip: You can use any traversal method, comparing each node's value as you visit it.
Challenge: Binary Search Tree (BST)
This is a classic variant of the binary tree. In a binary search tree, for any node:
- Itsleft subtreeall nodes' values in the < the node's value.
- Itsright subtreeall nodes' values in the > the node's value.
Your challenge is:
- Create a class that implements
insert_into_bst(root, value)function that inserts a value into the correct position in the binary search tree. - Create a class that implements
search_in_bst(root, value)function that uses the properties of a BST for efficient search (average time complexity O(log N)).