C语言实现计算树的深度的方法

时间:2021-07-18 09:36:22

本文实例讲述了C语言实现计算树的深度的方法。是算法设计中常用的技巧。分享给大家供大家参考。具体方法如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
* Copyright (c) 2011 alexingcool. All Rights Reserved.
*/
#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;
}

希望本文所述实例对大家C程序算法设计的学习有所帮助。