当前位置:主页 > 软件编程 > C代码 >

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

时间:2020-10-29 14:26:55 | 栏目:C代码 | 点击:

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

/* 
* 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程序算法设计的学习有所帮助。

您可能感兴趣的文章:

相关文章