InterviewSolution
| 1. |
Write a java syntax to input the height of a tree . Use a proper data type . |
|
Answer» ong>ANSWER: / C++ program to find height of tree #include using namespace std;
/* A BINARY tree NODE has data, pointer to left child and a pointer to right child */ class node { public: INT data; node* left; node* right; };
/* Compute the "maxDepth" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int maxDepth(node* node) { if (node == NULL) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node->left); int rDepth = maxDepth(node->right);
/* use the larger one */ if (lDepth > rDepth) return(lDepth + 1); else return(rDepth + 1); } }
/* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode(int data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL;
return(Node); }
// Driver code int main() { node *root = newNode(1);
root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5);
cout << "Height of tree is " << maxDepth(root); return 0; }
// This code is contributed by rathbhupendra |
|