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 parent reference 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 pp is the root node (isRoot(p)).
  • Generic Implementation Strategies:

    • Data encapsulation can be handled using an Object reference 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 raw Object references.

Calculating Node Depth and Tree Height

  • Node Depth Invariants:

    • If node pp is the root node, the depth of pp is 00.
    • If node pp is not the root node, the depth is calculated recursively as 1+depth(parent(p))1 + \text{depth}(\text{parent}(p)).
  • Recursive Algorithm for Depth (depth(p)):

    • If isRoot(p) is true, return 00
    • Else, return 1+depth(parent(p))1 + \text{depth}(\text{parent}(p))
  • Step-by-Step Recursive Trace of depth(B):

    • Consider a tree with root node AA and child node BB (where parent of BB is AA).
    • Call 1: depth(B) is executed.
    • Check if node BB is the root node: isRoot(B) returns false.
    • Evaluate recursive statement: 1+depth(parent(B))1 + \text{depth}(\text{parent}(B)), which resolves to 1+depth(A)1 + \text{depth}(A).
    • Call 2: depth(A) is executed.
    • Check if node AA is the root node: isRoot(A) returns true.
    • Base case reached: depth(A) returns 00
    • Final Evaluation: The original call resolves to 1+0=11 + 0 = 1. The depth of node BB is 11
  • Height Calculation Considerations:

    • Determining height by iterating through nodes with a simple for loop over all children in an unoptimized manner is inefficient.
    • Efficient height algorithms compute depth recursively or leverage child subtrees systematically.

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 O(1)O(1) constant time when each node stores explicit reference variables to parent and child nodes.
  • Node Status Classification Helper Methods:

    • isInternal(p): Evaluates whether node pp is an internal node by checking if pp has at least one child node.
    • isExternal(p): Evaluates whether node pp is an external node (leaf) by checking if pp has zero children.
    • isRoot(p): Evaluates whether node pp is the root by checking if its parent reference is null.

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 vv storing key key(v)\text{key}(v):
    • For every node uu located in the left subtree of vv, key key(u)\text{key}(u) satisfies key(u)<key(v)\text{key}(u) < \text{key}(v).
    • For every node ww located in the right subtree of vv, key key(w)\text{key}(w) satisfies key(w)>key(v)\text{key}(w) > \text{key}(v).
  • 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 66:
    • All keys residing in the left subtree of 66 must be strictly less than 66
    • All keys residing in the right subtree of 66 must be strictly greater than 66
    • Violation Analysis: If key 77 is located in the left subtree of root 66, it violates the binary search tree property because 7>67 > 6
    • Correct Positioning of Key 77:
    • Compare 77 with root 66: 7>67 > 6, so navigate to the right of 66
    • Encounter existing node with key 88: 7<87 < 8, so navigate to the left of 88
    • Key 77 belongs as the left child of node 88

Binary Search Tree Algorithms: Searching

  • Recursive Search Algorithm (treeSearch(k, p)):

    • Inputs: Target key kk to search for, and current node pp (initially set to root node vv).
    • Logic Steps:
    1. If node pp is null or an external empty node, key kk is not present in the tree.
    2. If k<key(p)k < \text{key}(p), recursively search the left subtree: treeSearch(k, left(p)).
    3. If k==key(p)k == \text{key}(p), target key kk is found; return true or node pp
    4. If k>key(p)k > \text{key}(p), recursively search the right subtree: treeSearch(k, right(p)).
  • Detailed Trace: Searching for Target Key 44 in Tree Rooted at Key 66:

    • Step 1: Call treeSearch(4, node_6).
    • Root node 66 exists (null check passes).
    • Evaluate condition: Is 4<64 < 6? True. Recurse into left subtree.
    • Step 2: Call treeSearch(4, node_2) (left child of 66 is node 22).
    • Node 22 exists.
    • Evaluate condition: Is 4<24 < 2? False.
    • Evaluate condition: Is 4==24 == 2? False.
    • Condition 4>24 > 2 holds. Recurse into right subtree.
    • Step 3: Call treeSearch(4, node_4) (right child of 22 is node 44).
    • Node 44 exists.
    • Evaluate condition: Is 4<44 < 4? False.
    • Evaluate condition: Is 4==44 == 4? True. Key found! Return true.
  • Trace: Searching for Missing Target Key 33:

    • Search compares 3<63 < 6 (moves left to node 22).
    • Compares 3>23 > 2 (moves right to node 44).
    • Compares 3<43 < 4 (moves left to left child of node 44).
    • Left child of node 44 is null (end of branch reached).
    • Search concludes key 33 is not in the tree.

Binary Search Tree Algorithms: Insertion

  • Insertion Protocol:

    • To insert key kk, first execute treeSearch(k, root).
    • Assumption: Key kk does not already exist in the tree (no duplicates).
    • Let ww be the empty/null location reached when treeSearch terminates.
    • Insert a new node containing key kk directly at position ww
  • Insertion Examples:

    • Inserting Key 33:
    • treeSearch(3, root) traverses root 66 -> node 22 -> node 44 -> null left child position of 44
    • Position ww is the left child spot of node 44. Insert key 33 at ww
    • Inserting Key 55:
    • Compare 5<65 < 6: Move left to node 22
    • Compare 5>25 > 2: Move right to node 44
    • Compare 5>45 > 4: Move right to empty position of node 44
    • Insert key 55 as the right child of node 44

Binary Search Tree Algorithms: Deletion

  • Pre-Deletion Requirement:

    • Always execute treeSearch(k, root) to locate target key kk and verify its existence before attempting removal.
  • 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 88 (where 88 has no children).
    • Search finds node 88
    • Because node 88 has zero children, simply unbind/remove node 88
  • 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 44 (which has a single child node with key 55).
    • Search finds node 44
    • Node 44 has one child (node 55).
    • Delete node 44 and connect node 55 directly to the parent of node 44
    • 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 findMax operation on the left subtree).
    • Example based on in-order traversal sequence 2,3,4,5,6,7,8,92, 3, 4, 5, 6, 7, 8, 9:
      • Target node to delete has key 44
      • In-order sequence preceding 44 is key 33
      • Replace key 44 with key 33
      • Remove the original node 33 (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 findMin operation on the right subtree).