Trees are hierarchical structures. Graphs are networks of connected nodes.
Tree Types
- Binary Tree — max 2 children
- BST — left < parent < right
- AVL — self-balancing BST
Trees are hierarchical structures. Graphs are networks of connected nodes.
# Binary Search Tree
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def inorder(node): if node: inorder(node.left) print(node.val, end=" ") inorder(node.right) # Build tree root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(6) root.left.left = TreeNode(1) root.left.right = TreeNode(3) print("Inorder traversal:") inorder(root) # 1 2 3 4 6
What is the time complexity of searching in a balanced BST?
O(log n) — each comparison halves the search space.
In a BST, where are smaller values stored?
In a BST, left children are smaller than parent.
A tree is a hierarchical structure with no cycles. A graph can have cycles and multiple connections between nodes.