C語言實現(xiàn)計算樹的深度的方法
更新時間:2014年09月16日 16:06:18 投稿:shichen2014
這篇文章主要介紹了C語言實現(xiàn)計算樹的深度的方法,針對數(shù)據(jù)結(jié)構(gòu)中樹進行操作的方法,在算法設(shè)計中比較常見,需要的朋友可以參考下
本文實例講述了C語言實現(xiàn)計算樹的深度的方法。是算法設(shè)計中常用的技巧。分享給大家供大家參考。具體方法如下:
/* * 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程序算法設(shè)計的學(xué)習(xí)有所幫助。
相關(guān)文章
C++實現(xiàn)inline hook的原理及應(yīng)用實例
這篇文章主要介紹了C++實現(xiàn)inline hook的原理及應(yīng)用,需要的朋友可以參考下2014-08-08