Tree
Tree
Parts of a Tree
1. Node: Contains a value or data structure.
2. Root Node: Topmost node of the tree (only one per tree).
3. Parent Node: Directly above a given node.
4. Child Node: Directly below a given node.
5. Leaf Node: A node with no children.
6. Depth/Level: Distance from the root to a node.
7. Tree Height: Maximum depth of the tree.
8. Edge: Connection between two nodes.
9. Subtree: A node and all its descendants.
10. Ancestor: A node along the path from the root to the given node.
11. Degree of a Node: Number of children a node has.
Types of Trees
1. Binary Tree: Each node has at most two children.
Examples: Binary Search Tree (BST), Binary Heap.
2. Ternary Tree: Each node has at most three children.
3. Nary Tree: Nodes can have more than three children.
4. Balanced Tree: The left and right subtrees' height differ by at most 1.
5. General Tree: No restrictions on the number of children per node.
Basic Operations
1. Create: Initialize a tree.
2. Insert: Add data to the tree.
3. Search: Find specific data in the tree.
4. Traversal:
DepthFirst Search (DFS)
BreadthFirst Search (BFS)
Binary Search Tree (BST)
Definition: A binary tree where the left subtree contains values less than the root, and the right
subtree contains values greater than the root.
Operations:
1. Insertion:
Compare the element with the root and decide whether to go left or right.
Place it as a leaf node in the appropriate position.
2. Search:
Start at the root and traverse left or right based on the key.
Continue until the key is found or the tree ends.
3. Deletion:
Node with One Child: Replace with its child.
Node with Two Children: Replace with the inorder successor.
Traversal Techniques
1. DepthFirst Search (DFS):
Preorder: Root → Left → Right
Inorder: Left → Root → Right
Postorder: Left → Right → Root