1+ /*
2+ * Algorithm: Height of Binary Tree
3+ * Description: Recursively finds the maximum number of edges on the path from the root to any leaf node.
4+ * Time Complexity: O(n)
5+ * Space Complexity: O(h) // Where 'h' is the height of the tree, due to recursion stack
6+ * Author: Adi-3108
7+ */
8+
9+ #include < iostream>
10+ #include < algorithm> // Required for max
11+
12+ using namespace std ;
13+ // 1. Structure Definition
14+ struct TreeNode {
15+ int val;
16+ TreeNode *left;
17+ TreeNode *right;
18+
19+ // Constructor
20+ TreeNode (int x) : val(x), left(NULL ), right(NULL ) {}
21+ };
22+
23+ /* *
24+ * @brief Recursively calculates the height of the binary tree.
25+ * * Height is defined as the number of edges on the longest path from the root to a leaf.
26+ * * @param root The root of the binary tree (or subtree).
27+ * @return The height of the tree (number of edges).
28+ */
29+ int calculateHeight (TreeNode* root) {
30+ // Base case: An empty tree (NULL) has a height of -1 (so a single node returns 0).
31+ if (root == NULL ) {
32+ return -1 ;
33+ }
34+
35+ // Recursively find the height of the left and right subtrees
36+ int left_height = calculateHeight (root->left );
37+ int right_height = calculateHeight (root->right );
38+
39+ // The height of the current tree is 1 (for the current node/edge)
40+ // plus the maximum height of the subtrees.
41+ return 1 + max (left_height, right_height);
42+ }
43+
44+ // Test function with modern C++ features
45+ void testCalculateHeight () {
46+ // Test Case 1: Skewed Tree (Height = 3)
47+ // 1 -> 2 -> 3 -> 4
48+ TreeNode *root1 = new TreeNode (1 );
49+ root1->left = new TreeNode (2 );
50+ root1->left ->left = new TreeNode (3 );
51+ root1->left ->left ->left = new TreeNode (4 );
52+ // for verification We are Printing the expected height
53+ cout << " Test Case 1 (Skewed Tree):\n " ;
54+ cout << " Expected Height: 3, Actual Height: " << calculateHeight (root1) << endl;
55+
56+ // Test Case 2: Balanced Tree (Height = 2)
57+ // 1
58+ // / \
59+ // 2 3
60+ // / \
61+ // 4 5
62+ TreeNode *root2 = new TreeNode (1 );
63+ root2->left = new TreeNode (2 );
64+ root2->right = new TreeNode (3 );
65+ root2->left ->left = new TreeNode (4 );
66+ root2->left ->right = new TreeNode (5 );
67+
68+ cout << " \n Test Case 2 (Balanced Tree):\n " ;
69+
70+ // for verification We are Printing the expected height
71+ cout << " Expected Height: 2, Actual Height: " << calculateHeight (root2) << endl;
72+
73+ // Clean up memory
74+ delete root1->left ->left ->left ;
75+ delete root1->left ->left ;
76+ delete root1->left ;
77+ delete root1;
78+
79+ delete root2->left ->left ;
80+ delete root2->left ->right ;
81+ delete root2->left ;
82+ delete root2->right ;
83+ delete root2;
84+ }
85+
86+ int main () {
87+ testCalculateHeight ();
88+ return 0 ;
89+ }
0 commit comments