This article details the implementation of a C++ program designed too construct a binary tree from a preorder traversal string and subsequently calculate its depth. The program utilizes a pointer-based representation for the binary tree.
The input is a preorder traversal string where the '#' character signifies a null node (an empty subtree). For example, the string ABC##DE#G##F### represents a binary tree.
- Data Structure Definition
BiTNode: Represents a node in the binary tree. It contains a data field (TElemType, a character in this case) and two pointers,lchildandrchild, to its left and right children, respectively.BiTree: A type alias for a pointer to aBiTNode, representing the binary tree itself.
- Binary Tree Construction (
CreateBiTreefunction)
This function recursively builds a binary tree based on the preorder traversal input. It reads characters one by one:
- If the character read is '#', it signifies a null node, and the current subtree pointer is set to
NULL. - Otherwise, a new node is created, the character is assigned to its data field, and the function recursively calls itself to construct the left and right subtrees.
The input reading is designed to handle multiple test cases. If reading fails (e.g., end-of-file), the program exits.
void CreateBiTree(BiTree &T) {
TElemType ch;
if (!(cin >> ch)) { // Exit if input fails (EOF)
exit(0);
}
if (ch == '#') {
T = NULL; // '#' represents a null node
} else {
T = new BiTNode; // Allocate memory for the new node
T->data = ch;
CreateBiTree(T->lchild); // Recursively build the left subtree
CreateBiTree(T->rchild); // Recursively build the right subtree
}
}
- Depth Calculation (
Depthfunction)
This function computes the depth of the binary tree. The depth is defined as the number of nodes along the longest path from the root node down to the farthest leaf node.
- If the tree is empty (
TisNULL), its depth is 0. - Otherwise, it recursively calculates the depth of the left and right subtrees. The depth of the current tree is 1 (for the current node) plus the maximum of the depths of its left and right subtrees.
int Depth(BiTree T) {
if (T == NULL) {
return 0; // Depth of an empty tree is 0
} else {
int leftDepth = Depth(T->lchild);
int rightDepth = Depth(T->rchild);
// Return 1 + the maximum depth of the subtrees
return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
}
}
- Tree Destruction (
DestroyBitreefunction)
This function is responsible for dealllocating the memory occupied by the binary tree to prevent memory leaks. It uses a post-order traversal approach:
- If the current node
Tis notNULL:- Recursively call
DestroyBitreeon the left child. - Recursively call
DestroyBitreeon the right child. - Free the memory allocated for the current node.
- Set the pointer
TtoNULLto indicate it's no longer valid.
- Recursively call
void DestroyBitree(BiTree& T) {
if (T) {
DestroyBitree(T->lchild); // Destroy left subtree
DestroyBitree(T->rchild); // Destroy right subtree
delete T; // Free the current node
T = NULL; // Set pointer to NULL
}
}
- Main Function (
main)
The main function orchestrates the process. It continuously loops:
- In each iteration, it calls
CreateBiTreeto build a tree from user input. - Then, it calls
Depthto calculate the tree's depth and prints the result. - Finally, it calls
DestroyBitreeto clean up the memory before the next iteration.
int main() {
BiTree tree = NULL; // Initialize tree pointer
while (1) { // Loop indefinitely for multiple test cases
CreateBiTree(tree);
cout << Depth(tree) << endl;
DestroyBitree(tree);
}
return 0;
}
Example Usage:
Input:
a#b#cdef#####
a##
Output:
6
1