Untitled
unknown
plain_text
a year ago
1.2 kB
6
Indexable
5) height of binary tree #include <stdio.h> #include <stdlib.h> // Definition for a binary tree node struct Node { int data; struct Node* left; struct Node* right; }; // Function to create a new node struct Node* newNode(int data) { struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return node; } // Function to find the height of a binary tree int height(struct Node* root) { if (root == NULL) { return 0; } else { // Compute the height of the left and right subtrees int leftHeight = height(root->left); int rightHeight = height(root->right); // Return the maximum of left and right subtree heights, plus 1 for the current level return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1; } } int main() { // Example usage struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Height of the binary tree is: %d\n", height(root)); return 0; }
Editor is loading...
Leave a Comment