TREEliB Documentation

Author: Amir Sakib Saad

54 Binary Tree Operations

.Create(array)

The Create function constructs a binary tree from a given list (array). It initializes the root node with the first element and then iterates through the list, assigning left and right child nodes in a level-order manner. If an element is None, it represents an absence of a node at that position. The function maintains a queue (nodes) to track nodes whose children need to be assigned. It ensures that elements are processed sequentially, forming a complete binary tree structure. The function returns the root node of the generated tree. If the input list is empty, it returns None.

.printIN(array)

The printIN function prints the binary tree in in-order traversal (Left, Root, Right). It first constructs the tree using the Create method and then calls the helper function helper_printIN, which performs a recursive traversal. The helper function: (1) Recursively visits the left subtree. (2) Prints the current node's value. (3) Recursively visits the right subtree. If the root is None, it returns without printing anything. This function ensures that nodes are printed in ascending order for a Binary Search Tree (BST).

.printPOST(array)

The printPOST function prints the binary tree using postorder traversal (Left, Right, Root). It first constructs the tree using the Create method and then calls the recursive helper function helper_printPOST. The helper function follows these steps: (1) Recursively visits the left subtree. (2) Recursively visits the right subtree. (3) Prints the current node's value. If the root is None, it returns without printing anything. This traversal is useful for deleting trees and evaluating expression trees.

.printPRE(array)

The printPRE function prints the binary tree using preorder traversal (Root, Left, Right). It first constructs the tree using the Create method and then calls the recursive helper function helper_printPRE. The helper function follows these steps: (1) Prints the current node's value. (2) Recursively visits the left subtree. (3) Recursively visits the right subtree. If the root is None, it returns without printing anything. This traversal is useful for copying trees and prefix expression evaluations.

.printLVL(array)

The printLVL function prints the binary tree using level-order traversal (Breadth-First Search). It first constructs the tree using the Create method and then processes nodes level by level using a queue. Steps: (1) If the tree is empty, return None. (2) Initialize a queue with the root node. (3) Process each node: Print its value. Add its left and right children (if they exist) to the queue. (4) Continue until all nodes are printed. This traversal is useful for finding the shortest path and understanding tree structure layer by layer.

.CountNodes(array)

The CountNodes function counts the total number of nodes in a binary tree. It first constructs the tree using the Create method and then calls the recursive helper function helper_CountNodes. The helper function follows these steps: (1) If the root is None, it returns the count as is. (2) It recursively counts nodes in the left and right subtrees. (3) It returns 1 + L + R, where L and R are the counts of the subtrees. This function efficiently determines the tree size using a depth-first approach.

.invert(array)

The invert function flips a binary tree by swapping the left and right children of every node. It first constructs the tree and calls the recursive helper function helper_invert. The steps are: (1) If the root is None, return None. (2) Recursively swap the left and right subtrees at each node. (3) After inversion, perform a level-order traversal to print the tree. This mirrors the tree structure and is useful in tasks like image reflection.

.MAXdepth(array)

The MAXdepth function calculates the maximum depth (or height) of a binary tree. It constructs the tree and calls the recursive helper function helper_MAXdepth. The steps are: (1) If the root is None, return 0. (2) Recursively calculate the depth of the left and right subtrees. (3) Return the greater depth between the two subtrees plus 1 for the current node. This helps determine the longest path from the root to a leaf.

.MINdepth(array)

The MINdepth function calculates the minimum depth of a binary tree, representing the shortest path from the root to a leaf node. It uses the helper function helper_MINdepth with these steps: (1) If the root is None, return 0. (2) If a subtree is missing, return 1 + depth of the existing subtree. (3) Otherwise, return 1 + the minimum depth of both subtrees. This is useful for shortest path calculations.

.getDiameter(array)

The getDiameter function calculates the diameter of a binary tree, which is the longest path between any two nodes. Using the helper_getDiameter function, it follows these steps: (1) If the root is None, return 0. (2) Calculate the max depth of subtrees (L and R). (3) Recursively calculate the diameter of subtrees (dL and dR). (4) The diameter is the maximum of (L + R) or the maximum diameters of the subtrees (dL, dR).

.checkBalanced(array)

The checkBalanced function verifies if a binary tree is balanced (subtree heights differ by no more than one). It uses helper_checkBalanced to: (1) Return True if the root is None. (2) Calculate heights of left and right subtrees. (3) Determine balance if the absolute height difference is ≤ 1 and both subtrees are recursively balanced.

.checkSame(arrayA, arrayB)

The checkSame function determines if two binary trees are identical in structure and data. It constructs both trees and uses helper_checkSame to: (1) Return True if both roots are None. (2) Return False if only one root is None. (3) If current node data matches, recursively check left and right subtrees. It returns True only if all corresponding nodes match.

.isSUB(mainTree, subTree)

The isSUB function checks if a binary tree (sub) is a subtree of another (main). It uses helper_isSUB to: (1) Return True if the sub tree is None. (2) Return False if main is None but sub is not. (3) Check if trees are identical at the current node using helper_checkIDN. (4) Recursively check the left and right subtrees of the main tree.

.margeTREE(arrayA, arrayB)

The margeTREE function merges two binary trees by summing node values at corresponding positions. It uses helper_margeTREE to: (1) Return None if both nodes are missing. (2) Use the value from the existing node if one is None. (3) Create a new node with the sum of values from both trees. (4) Recursively merge subtrees and print the result in level order.

.pathSUM(array, target)

The pathSUM function calculates the sum of the path from the root to a target node. It uses helper_pathSUM to: (1) accumulate values starting from 0. (2) If the current node matches the target, return the accumulated sum. (3) Recursively search left and right subtrees. (4) Return the sum if the target is found, otherwise return None.

.TpathSUM(array, target)

The TpathSUM function returns all paths where the sum of node values equals a target. It uses helper_TpathSUM to: (1) Track the current path and sum. (2) Append current node values to the path list. (3) If the current sum matches the target, add the path to results. (4) Recursively check subtrees and backtrack by popping the last element.

.MAXpathSUM(array)

The MAXpathSUM function finds the highest sum along any path in the tree. It uses helper_MAXpathSUM to: (1) Return 0 for path sum and negative infinity for max sum if the node is None. (2) Recursively compute max sums from subtrees, ignoring negative sums. (3) Update the global maximum considering the path through the current root. (4) Return the maximum path sum found.

.leafSM(arrayA, arrayB)

The leafSM function checks if the leaf nodes of two trees form the same sequence. It constructs two trees and uses helper functions to: (1) Traverse the trees and collect all leaf node values into lists. (2) Compare the resulting lists. (3) Return True if the leaf sequences are identical in value and order.

.rightV(array)

The rightV function calculates the right side view of a binary tree. It uses helper_rightV to perform a right-first depth-first traversal: (1) It tracks visited levels. (2) If a level is visited for the first time, the node is added to the result. (3) It prioritizes the right subtree over the left to capture the rightmost nodes at each depth.

.leftV(array)

The leftV function calculates the left side view of a binary tree. It uses helper_leftV to perform a left-first depth-first traversal: (1) It tracks visited levels. (2) If a level is visited for the first time, the node is added to the result. (3) It prioritizes the left subtree over the right to capture the leftmost nodes at each depth.

.topV(array)

The topV function calculates the view of the tree from above. It uses helper_topV with horizontal distance (hd): (1) Use a queue for breadth-first traversal, tracking hd. (2) If a specific hd is encountered for the first time, add the node to the view dictionary. (3) Sort by hd and print values from left to right.

.bottomV(array)

The bottomV function calculates the view of the tree from below. It uses helper_bottomV with horizontal distance (hd): (1) Use a queue for breadth-first traversal. (2) Update the view dictionary with the current node for every hd encountered (overwriting previous ones). (3) This ensures the bottommost nodes are stored. (4) Sort by hd and print the values.

.checkSYM(array)

The checkSYM function determines if a binary tree is a mirror image of itself (symmetric around its center). It uses the helper function helper_checkSYM to recursively compare subtrees: (1) If both subtrees are None, return True. (2) If only one is None, return False. (3) If nodes exist, check if their values match and recursively compare the outer pairs (left-left vs right-right) and inner pairs (left-right vs right-left).

.checkCOM(array)

The checkCOM function verifies if a binary tree is "complete," meaning all levels are filled except possibly the last, which is filled left-to-right. Using a level-order traversal (queue): (1) It processes nodes, marking when a missing child is found. (2) If any non-None node appears after a missing node, it returns False. (3) Otherwise, it returns True, confirming the structure is suitable for binary heaps.

.MAXwidth(array)

The MAXwidth function finds the maximum number of nodes present at any single level of the tree. It uses a level-order traversal: (1) Initialize a queue with the root. (2) For each level, compare the queue size (number of nodes at that level) to the current maximum. (3) Process children for the next level. (4) Return the largest width found.

.FlipEQ(arrayA, arrayB)

The FlipEQ function checks if two trees are "flip equivalent," meaning one can be transformed into the other by swapping left/right children. The helper function checks: (1) If nodes are None or values differ, return accordingly. (2) Recursively check if subtrees match directly OR if they match after a swap. (3) Return True if either condition holds for all nodes.

.FlipCLK(array)

The FlipCLK function performs a specific clockwise rotation of the tree structure. It uses helper_FlipCLK to: (1) Make the root's left child the new root. (2) Move the original root to become the right child of the new root. (3) Reconnect the new root's original left child. (4) Print the modified tree using level-order traversal.

.FlipACLK(array)

The FlipACLK function flips the tree in an anti-clockwise manner by recursively swapping the left and right children of every node. The steps are: (1) Recursively swap children for the current node. (2) Perform the swap on both left and right subtrees. (3) Print the resulting tree using level-order traversal. This effectively mirrors the tree.

.findLv(array)

The findLv function identifies the largest value in the binary tree using Depth-First Search (DFS). It uses helper_findLv to: (1) Initialize a maximum tracker (MAX). (2) Compare the current node's data against MAX, updating it if larger. (3) Recursively traverse left and right subtrees to ensure every node is checked. (4) Return the highest value found.

.findSv(array)

The findSv function identifies the smallest value in the binary tree using Depth-First Search (DFS). It uses helper_findSv to: (1) Initialize a minimum tracker (MIN). (2) Compare the current node's data against MIN, updating it if smaller. (3) Recursively traverse left and right subtrees. (4) Return the lowest value found.

.deleteNODE(array, target)

The deleteNODE function removes a specific node while maintaining tree structure. The steps are: (1) Use level-order traversal to find the target node and the very last node (rightmost leaf). (2) Replace the target node's value with the last node's value. (3) Delete the last node from its original position. (4) Return the modified tree.

.addNODE(array, node)

The addNODE function inserts a new node into the first available position to maintain a complete tree structure. Steps: (1) If the tree is empty, set the new node as root. (2) Perform a level-order traversal. (3) Add the node as a left child if missing, or a right child if missing. (4) Exit immediately once the node is placed.

.Serialize(array)

The Serialize function converts a binary tree into a list representation using level-order traversal (BFS). It constructs the tree, iterates through nodes to append their values (including None for missing children) to a result list, and finally trims trailing None values to ensure a concise representation.

.Deserialize(array)

The Deserialize function reconstructs a binary tree from a serialized list. It establishes the first element as the root and utilizes a queue to manage level-order reconstruction, mapping subsequent list elements as left and right children for each parent node in the queue.

.checkIDN(arrayA, arrayB)

The checkIDN function determines if two binary trees are identical in both structure and data. Using a recursive helper, it compares nodes at each position; if both nodes are None, they match, otherwise, it verifies that their data is equal and recursively validates their left and right subtrees.

.CLDsum(array)

The CLDsum function verifies the Children Sum Property, where every internal node's value must equal the sum of its children's values. It recursively traverses the tree, treating None children as zero, and returns True only if the condition holds for every node in the structure.

.getCLD(array, target)

The getCLD function retrieves the immediate children of a specified target node. It searches the tree for the target value and returns a list containing the values of its left and right children, returning None if the target is not found or an empty list if it is a leaf.

.KthNODE(array, K)

The KthNODE function identifies the first node encountered at a specific distance (K levels) from the root. It navigates the tree structure to the specified depth and returns the value of the node found at that level, or None if the tree depth is less than K.

.getLVL(array, target)

The getLVL function calculates the depth or level of a specific target node within the tree. It traverses the structure to find the node and returns its distance from the root, returning -1 if the target node does not exist in the tree.

.checkFLD(array)

The checkFLD function checks if a binary tree is foldable, meaning its left and right subtrees are structural mirror images. It uses a recursive helper to ensure that for every pair of nodes, the left-child of one matches the structure of the right-child of the other.

.checkMIR(arrayA, arrayB)

The checkMIR function determines if two binary trees are mirror images of each other. It verifies that the left subtree of the first tree is a structural and data reflection of the right subtree of the second tree, and vice versa, using a recursive helper function.

.checkPRF(array)

The checkPRF function checks if a binary tree is "perfect," meaning all internal nodes have exactly two children and all leaf nodes reside at the same depth. It calculates the depth of the leftmost path and ensures every other path matches this length while maintaining full branching.

.checkCSN(array, node1, node2)

The checkCSN function identifies if two nodes are cousins. To qualify, both nodes must exist at the exact same depth (level) within the tree but must originate from different parent nodes.

.LCA(array, node1, node2)

The LCA function finds the Lowest Common Ancestor of two specified nodes. It identifies the deepest node in the tree that serves as an ancestor to both targets, using a recursive approach that bubbles up the common node once both targets are located in separate subtrees.

.printANC(array, target)

The printANC function retrieves all parent nodes leading from the root to a specific target node. It recursively explores the tree and, upon finding the target, builds a list of every node encountered along that specific search path.

.printDANC(array, target)

The printDANC function identifies and returns all descendants of a specific target node. It first locates the node using a recursive search and then performs a top-down traversal to gather all children and sub-children into a single list.

.findDST(array, node1, node2)

The findDST function calculates the shortest distance (number of edges) between two nodes. It identifies their Lowest Common Ancestor (LCA) and sums the path lengths from the LCA to each respective node.

.checkFULL(array)

The checkFULL function determines if a tree is a "Full Binary Tree," where every node must have either zero or exactly two children. It recursively validates that no node in the structure possesses only a single child.

.changeNODE(array, prev, new)

The changeNODE function searches for a node with a specific value and updates it to a new value. After the modification, it performs a level-order traversal to display the updated state of the tree.

.findDNST(array)

The findDNST function calculates the density of the binary tree, defined as the ratio of the total number of nodes to the tree's maximum height. This metric provides insight into how "filled" or balanced the tree structure is.

.getPNT(array, target)

The getPNT function retrieves the immediate parent of a specific target node. It recursively traverses the tree to find the node whose left or right child matches the target value, returning the parent's data or None if no parent exists.

.getSIB(array)

The getSIB function identifies sibling relationships within the tree. Using level-order traversal, it detects nodes sharing the same parent and returns a dictionary where each node is mapped to its corresponding sibling.

.checkAVL(array)

The checkAVL function determines if a binary tree is height-balanced. It verifies that for every node, the height difference (balance factor) between the left and right subtrees is no more than 1, a key property of AVL trees.

.checkBST(array)

The checkBST function validates whether the tree is a Binary Search Tree. It recursively ensures that for every node, all values in its left subtree are smaller and all values in its right subtree are larger, using a min/max boundary approach.

.rTOn(array, target)

The rTOn function calculates the distance (number of edges) from the root to a specified target node. It uses a Breadth-First Search (BFS) to find the node and returns its depth level relative to the root.

Installation Guide

Google Colab

In Google Colab, simply use the following command in a code cell to install the package:

!pip install binaryTREE-operations

VS Code

In Visual Studio Code (VS Code), open the terminal and run the following:

pip install binaryTREE-operations

Jupyter Notebook

To install the package in Jupyter Notebook, run the following command in a code cell:

!pip install binaryTREE-operations

After installation, you can import and use the library:

from binaryTREE import BinaryTree
Binarytree = BinaryTree()
VISIT PyPI PACKAGE →