编程之美3.8求二叉树中节点的最大距离

来源:互联网 发布:什么是数据清洗 编辑:程序博客网 时间:2024/05/21 07:48

今天看了这道题,感觉作者的解法空间消耗太大,所以想出以下解决方案,由于代码本身比较简单所以我就不解释了,请看代码:

#include<stdio.h>#include<stdlib.h>typedef struct Node* link;struct Node{link left;link right;int key;};static link head;link NEW(link left, link right, int key){link templink = (link)malloc(sizeof(struct Node));templink->left = left;templink->right = right;templink->key = key;}link InsertToBinaryTree(link h,int key){if (NULL == h) return NEW(NULL, NULL, key);if (h->key > key)h->left = InsertToBinaryTree(h->left, key);else {h->right = InsertToBinaryTree(h->right, key);}return h;}int getMAXLengthBetweenTwoNodes(link h, int *MAXLength){int Lheight = 0;int Rheight = 0;if (NULL == h) return -1;Lheight = getMAXLengthBetweenTwoNodes(h ->left, MAXLength);Rheight = getMAXLengthBetweenTwoNodes(h ->right, MAXLength);if (Lheight + Rheight + 2 > *MAXLength)*MAXLength = Lheight + Rheight + 2;return (Lheight > Rheight ? Lheight : Rheight) + 1;}int GetMAXLengthBetweenTwoNodes(link head){if (NULL == head) return -1;int MAXLength = 0;getMAXLengthBetweenTwoNodes(head, &MAXLength);return MAXLength;}void main(){int data[] = {6, 7, 8, 3, 4, 5, 6, 9};int i = 0;        //创建BST        for (i = 0; i < sizeof(data) / sizeof(data[0]); ++ i)head = InsertToBinaryTree(head, data[i]);        //计算最大距离        printf("MAXLENGTH = %d\n", GetMAXLengthBetweenTwoNodes(head));//测试结果:6}


*最后发现跟这个博客的思想一样:http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html

原创粉丝点击