Tree Operations
Trees are hierarchical data structures that can be manipulated using various operations. Some common operations on trees include insertion, deletion, searching, and traversal.
Insertion
To insert a new node into a tree, we need to find the appropriate position to maintain the tree's ordering property. Here's an example of how to insert a node into a binary search tree using a recursive approach in Python:
PYTHON
1# Tree node class
2
3class Node:
4 def __init__(self, value):
5 self.value = value
6 self.left = None
7 self.right = None
8
9# Insert a node
10
11def insert(root, value):
12 if root is None:
13 return Node(value)
14 else:
15 if value < root.value:
16 root.left = insert(root.left, value)
17 else:
18 root.right = insert(root.right, value)
19 return root
20
21# Create a binary search tree
22
23root = Node(50)
24insert(root, 30)
25insert(root, 70)
26insert(root, 20)
27insert(root, 40)
28insert(root, 60)
29insert(root, 80)
xxxxxxxxxx
80
postorder(root)
# Python - Tree Operations
# Tree node class
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert a node
def insert(root, value):
if root is None:
return Node(value)
else:
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
# Search for a value
def search(root, value):
if root is None or root.value == value:
return root
if value < root.value:
return search(root.left, value)
return search(root.right, value)
# Delete a node
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment