Binary Trees and Binary Search Trees: Data Structures and Operations
Binary Tree Node Representations and Implementations
Extended Node Structure (Parent-Referenced Nodes):
- Contains four primary fields:
element: Stores the data or payload of the node.left: Reference variable pointing directly to the left child node.right: Reference variable pointing directly to the right child node.parent: Reference variable pointing directly to the parent node.- Having a direct
parentreference allows bidirectional traversal up and down the tree structure. When adding a new node, memory allocation creates the node and links it to its parent node.
Simplified Node Structure:
- Contains three primary fields without an explicit parent reference:
element: Stores the node data.left: Reference to the left child node.right: Reference to the right child node.
Binary Tree Construction and Class Design:
- When initializing a binary tree structure, the initial node instantiated is the root node.
- Constructor options:
- Default constructor sets the root node reference to
null. - Parameterized constructor creates a root node populated with a specified initial element.
- Node status methods include a check to determine whether a given node is the root node (
isRoot(p)).
Generic Implementation Strategies:
- Data encapsulation can be handled using an
Objectreference variable, allowing nodes to store arbitrary data types. - A superior implementation strategy uses explicit generic type parameters (e.g.,
<T>) to ensure type safety rather than relying on rawObjectreferences.
- Data encapsulation can be handled using an
Calculating Node Depth and Tree Height
Node Depth Invariants:
- If node is the root node, the depth of is .
- If node is not the root node, the depth is calculated recursively as .
Recursive Algorithm for Depth (
depth(p)):- If
isRoot(p)is true, return - Else, return
- If
Step-by-Step Recursive Trace of
depth(B):- Consider a tree with root node and child node (where parent of is ).
- Call 1:
depth(B)is executed. - Check if node is the root node:
isRoot(B)returns false. - Evaluate recursive statement: , which resolves to .
- Call 2:
depth(A)is executed. - Check if node is the root node:
isRoot(A)returns true. - Base case reached:
depth(A)returns - Final Evaluation: The original call resolves to . The depth of node is
Height Calculation Considerations:
- Determining height by iterating through nodes with a simple
forloop over all children in an unoptimized manner is inefficient. - Efficient height algorithms compute depth recursively or leverage child subtrees systematically.
- Determining height by iterating through nodes with a simple
Time Complexity and Node Status Methods
Time Complexity Analysis:
- Querying structural relationships—such as accessing parent, left child, right child, sibling, children array, or node count—executes in constant time when each node stores explicit reference variables to parent and child nodes.
Node Status Classification Helper Methods:
isInternal(p): Evaluates whether node is an internal node by checking if has at least one child node.isExternal(p): Evaluates whether node is an external node (leaf) by checking if has zero children.isRoot(p): Evaluates whether node is the root by checking if its parent reference isnull.
Binary Search Tree (BST) Fundamentals and Properties
BST Structural Invariants:
- A Binary Search Tree is a binary tree storing key-value entries across its nodes.
- For any node storing key :
- For every node located in the left subtree of , key satisfies .
- For every node located in the right subtree of , key satisfies .
Handling Equal Keys:
- If duplicate/equal keys are permitted in the tree structure, a consistent policy must be chosen prior to construction:
- Policy 1: Consistently place equal keys into the left subtree.
- Policy 2: Consistently place equal keys into the right subtree.
- The chosen convention must be maintained strictly across all tree operations.
BST Structural Validation Example:
- Consider a tree with root key :
- All keys residing in the left subtree of must be strictly less than
- All keys residing in the right subtree of must be strictly greater than
- Violation Analysis: If key is located in the left subtree of root , it violates the binary search tree property because
- Correct Positioning of Key :
- Compare with root : , so navigate to the right of
- Encounter existing node with key : , so navigate to the left of
- Key belongs as the left child of node
Binary Search Tree Algorithms: Searching
Recursive Search Algorithm (
treeSearch(k, p)):- Inputs: Target key to search for, and current node (initially set to root node ).
- Logic Steps:
- If node is
nullor an external empty node, key is not present in the tree. - If , recursively search the left subtree:
treeSearch(k, left(p)). - If , target key is found; return true or node
- If , recursively search the right subtree:
treeSearch(k, right(p)).
Detailed Trace: Searching for Target Key in Tree Rooted at Key :
- Step 1: Call
treeSearch(4, node_6). - Root node exists (
nullcheck passes). - Evaluate condition: Is ? True. Recurse into left subtree.
- Step 2: Call
treeSearch(4, node_2)(left child of is node ). - Node exists.
- Evaluate condition: Is ? False.
- Evaluate condition: Is ? False.
- Condition holds. Recurse into right subtree.
- Step 3: Call
treeSearch(4, node_4)(right child of is node ). - Node exists.
- Evaluate condition: Is ? False.
- Evaluate condition: Is ? True. Key found! Return true.
- Step 1: Call
Trace: Searching for Missing Target Key :
- Search compares (moves left to node ).
- Compares (moves right to node ).
- Compares (moves left to left child of node ).
- Left child of node is
null(end of branch reached). - Search concludes key is not in the tree.
Binary Search Tree Algorithms: Insertion
Insertion Protocol:
- To insert key , first execute
treeSearch(k, root). - Assumption: Key does not already exist in the tree (no duplicates).
- Let be the empty/null location reached when
treeSearchterminates. - Insert a new node containing key directly at position
- To insert key , first execute
Insertion Examples:
- Inserting Key :
treeSearch(3, root)traverses root -> node -> node -> null left child position of- Position is the left child spot of node . Insert key at
- Inserting Key :
- Compare : Move left to node
- Compare : Move right to node
- Compare : Move right to empty position of node
- Insert key as the right child of node
Binary Search Tree Algorithms: Deletion
Pre-Deletion Requirement:
- Always execute
treeSearch(k, root)to locate target key and verify its existence before attempting removal.
- Always execute
Case 1: Target Node Has Zero Children (Leaf Node):
- Procedure: Locate node, unlink it from its parent, and remove it directly.
- Example: Deleting node with key (where has no children).
- Search finds node
- Because node has zero children, simply unbind/remove node
Case 2: Target Node Has Exactly One Child:
- Procedure: Locate target node, remove it, and replace its position with its single child node.
- Example: Deleting node with key (which has a single child node with key ).
- Search finds node
- Node has one child (node ).
- Delete node and connect node directly to the parent of node
- BST invariant remains completely preserved.
Case 3: Target Node Has Two Children:
- Target node cannot simply be removed without breaking tree connectivity.
- Replacement Option A (In-order Predecessor):
- Replace the target node's key with its in-order predecessor.
- The in-order predecessor is the largest key in the target node's left subtree (located via a
findMaxoperation on the left subtree). - Example based on in-order traversal sequence :
- Target node to delete has key
- In-order sequence preceding is key
- Replace key with key
- Remove the original node (which will have at most one child).
- Replacement Option B (In-order Successor):
- Replace the target node's key with its in-order successor.
- The in-order successor is the smallest key in the target node's right subtree (located via a
findMinoperation on the right subtree).