Binary Trees

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Binary Trees

Definition: A binary tree is a hierarchical data structure in which each node has at most two children, referred to as the left child and the
right child.
Basic Structure of a Node: python Copy code class TreeNode: def init(self, key): self.key = key self.left = None self.right = None
Terminology: Root: The topmost node in a tree. Parent: A node in a tree that has one or more child nodes. Child: A node in a tree that
has a parent. Leaf: A node in a tree that has no children. Subtree: A tree formed by a node and all its descendants. Types of Binary
Trees:
1. Full Binary Tree: Every node has either 0 or 2 children.
2. Complete Binary Tree: All levels are completely filled, except possibly the last level. Nodes are left-aligned.
3. Perfect Binary Tree: All internal nodes have exactly two children. All leaf nodes are at the same level.
4. Balanced Binary Tree: The height of the left and right subtrees of any node differs by no more than one. Ensures O(log n) time
complexity for insert, delete, and find operations. Tree Traversal:
5. Inorder Traversal (Left-Root-Right): python Copy code def inorder_traversal(root): if root: inorder_traversal(root.left) print(root.key,
end=' ') inorder_traversal(root.right)
6. Preorder Traversal (Root-Left-Right): python Copy code def preorder_traversal(root): if root: print(root.key, end=' ')
preorder_traversal(root.left) preorder_traversal(root.right)
7. Postorder Traversal (Left-Right-Root): python Copy code def postorder_traversal(root): if root: postorder_traversal(root.left)
postorder_traversal(root.right) print(root.key, end=' ') Time Complexity: Traversal: O(n) where n is the number of nodes. Search,
Insert, Delete: O(log n) for a balanced binary tree. In the worst case, for an unbalanced binary tree, these operations can take O(n)
time. Binary trees are widely used in computer science, and variations like binary search trees provide efficient searching and
sorting capabilities. Balancing techniques such as AVL trees and Red-Black trees are employed to maintain a balanced structure for
efficient operations. Understanding the properties and traversal methods is fundamental when working with binary trees.

You might also like