What is Tree?
- Tree is a data structure which has a hierarchy system.
Concepts & Words
- Node: each element of the tree
- Root: The uppermost node of the tree
- Parent: a node that is above another node
- Child: a node that is under another node
- Leaf: Nodes have no children
- Edge: The line connects nodes
- Level: The depth from the root (The level of the root is 0)
- Height: Max level of the tree
Features of Tree
- Hierarchy System: the relationship between subordinates and superiors
- No cycle: you can't go backward
- Connections: All nodes are connected from the root
- Distinct route: There is only one route between two random nodes
Implementing the Tree
Core Elements to implement
1. Node Class: Each node has the reference to its child node and data
2. Main Functions
- Insert: Adding a new node
- Search: Finding a specific value
- Traversal: Visiting all nodes
- Delete: Removing a node
- Preorder: Root -> Left -> Right
- Inorder: Left -> Root -> Right
- Postorder: Left -> Right -> Root
4. Recursion
- Tree is a basically recursive structure. Each node can be a small tree, so most of operations are implemented as recursion.
def tree_operation(node, data):
# Base case (exit condition)
if node is None:
return result
# Recursion Case (Calling itself)
if condtion:
return tree_operation(node.left, data)
else:
return tree_operation(node.right, data)
# Base case (exit condition)
if node is None:
return result
# Recursion Case (Calling itself)
if condtion:
return tree_operation(node.left, data)
else:
return tree_operation(node.right, data)
Pseudo Code For Implementing
Step 1. Define Node Class
Class Node:
data = value
left = None
right = None
Step 2. Insertion
function insert(root, new_value):
if root == None:
create a new node and return
if new value < root.data:
root.left = insert(root.left, new_value)
else:
root.right = insert(root.right, new_value)
return root
Step 3. Search
function search(root, target_value):
if root == None or root.data == target_value:
return root
if root.data > target_value:
return search(root.left, target_value)
else:
return search(root.right, target_value)
Comments
Post a Comment