-
Hajipur, Bihar, 844101
A Tree is a non-linear data structure used to represent hierarchical relationships. It starts with a root node and branches out to child nodes.
In Python, trees are commonly implemented using classes.
Term | Meaning |
---|---|
Root | Topmost node |
Child | Node directly connected to another node |
Parent | Node that has branches to children |
Leaf | Node with no children |
Subtree | A tree within another tree |
Binary Tree | Tree where each node has up to 2 children |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
root = Node(10)
root.left = Node(5)
root.right = Node(15)
# Tree structure:
# 10
# / \
# 5 15
def inorder(node):
if node:
inorder(node.left)
print(node.data, end=' ')
inorder(node.right)
inorder(root) # Output: 5 10 15
def preorder(node):
if node:
print(node.data, end=' ')
preorder(node.left)
preorder(node.right)
def postorder(node):
if node:
postorder(node.left)
postorder(node.right)
print(node.data, end=' ')
from collections import deque
def level_order(root):
if root is None:
return
queue = deque([root])
while queue:
current = queue.popleft()
print(current.data, end=' ')
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
File systems
HTML/XML DOM
Databases (B-trees, AVL trees)
Routing tables
Decision-making algorithms
Q1. Write a Python program to create a binary tree with root = 1 and two children 2 (left) and 3 (right).
Q2. Write a Python program to print all elements of the binary tree using Inorder traversal.
Q3. Write a Python program to count the total number of nodes in the binary tree.
Q4. Write a Python program to find the maximum value stored in the binary tree.
Q5. Write a Python program to add a new node to the left of a given node.
Q6. Write a Python program to traverse the binary tree using Postorder traversal.
Q7. Write a Python program to check if a binary tree is empty.
Q8. Write a Python program to find and print all leaf nodes of the binary tree.
Q9. Write a Python program to search for a specific value in the binary tree.
Q10. Write a Python program to convert a list of values into a binary tree structure (level-wise).
Q1: What is the top node of a tree called?
Q2: In a binary tree, how many children can a node have?
Q3: Which traversal visits root before children?
Q4: What does Inorder traversal of a binary tree return?
Q5: What type of traversal is used in BFS?
Q6: Which is a node with no children?
Q7: What data structure is used in level-order traversal?
Q8: Which traversal is Left → Right → Root?
Q9: Which tree type keeps data sorted?
Q10: Which Python module provides queues for BFS?