C language to calculate the depth of the tree method
- 2020-04-02 02:45:02
- OfStack
In this paper, an example is given to illustrate the method of calculating the depth of tree in C language. Is a common technique in algorithm design. Share with you for your reference. Specific methods are as follows:
#include <iostream>
using namespace std;
struct Node {
Node(int i = 0, Node *l = NULL, Node *r = NULL) : data(i), left(l), right(r) {}
int data;
Node *left;
Node *right;
};
Node* Construct() {
Node *node4 = new Node(7, NULL, new Node(3));
Node *node3 = new Node(4);
Node *node2 = new Node(12);
Node *node1 = new Node(5, node3, node4);
Node *root = new Node(10, node1, node2);
return root;
}
int GetTreeHeight(Node *root) {
if(root == NULL)
return 0;
return max(GetTreeHeight(root->left) + 1, GetTreeHeight(root->right) + 1);
}
void main() {
Node *root = Construct();
int height = GetTreeHeight(root);
cout << "tree height is: " << height << endl;
}
It is hoped that the examples described in this paper will be helpful to the learning of C program algorithm design.