第十一题:求二叉树任意两结点的最大距离

来源:互联网 发布:网络直播平台涉黄 编辑:程序博客网 时间:2024/04/29 13:33
#include "bst.h"#include <stdlib.h>#include <stdio.h>#define max(a,b) ((a)>(b) ? (a) : (b))/* ============================================================================ 求二叉树中任意两点的最大距离 ============================================================================ 思想:有三种可能:  (1)左子树中结点的最大距离  (2)右子树中结点的最大距离  (3)左子树的深度+右子树的深度  其中最大的就是所求。OK,递归。 */int getMaxDistance(Node* head,int &depth){if(head==NULL){depth=0;return 0;}int ld,rd,maxLeft,maxRight;maxLeft=getMaxDistance(head->pLeft,ld);maxRight=getMaxDistance(head->pRight,rd);depth=max(ld,rd)+1;return max(maxLeft,max(maxRight,ld+rd));}int main(){int s[]={234,34,24,4,34,2,3,6,67,34,255,266,280};int len=sizeof(s)/sizeof(int);Node* head=createList(s,len);int depth;printf("distance:%d\n",getMaxDistance(head,depth));pr_midOrder(head);free_afterOrder(head);getchar();return 0;}
其中头文件为
#ifndef BST_H_#define BST_H_#include <stdio.h>#include <stdlib.h>typedef struct node{int data;struct node* pLeft;struct node* pRight;} Node;//中序插入Node* insertList(int m, Node *pRoot){Node* pTmp;pTmp = (Node*) malloc(sizeof(Node));pTmp->data = m;pTmp->pLeft = NULL;pTmp->pRight = NULL;if (pRoot == NULL){return pTmp;}else{if (m < pRoot->data){if (pRoot->pLeft == NULL)pRoot->pLeft = pTmp;elseinsertList(m, pRoot->pLeft);}else{if (pRoot->pRight == NULL)pRoot->pRight = pTmp;elseinsertList(m, pRoot->pRight);}}return pRoot;}Node* createList(int a[], int n){int i = 0;Node* pNode = NULL;for (i = 0; i < n; i++){pNode = insertList(a[i], pNode);}return pNode;}//中序遍历void pr_midOrder(Node* pNode){if (pNode == NULL)return;pr_midOrder(pNode->pLeft);printf(" %d", pNode->data);pr_midOrder(pNode->pRight);}//后序释放void free_afterOrder(Node *pNode){if (pNode == NULL)return;if (pNode->pLeft == NULL && pNode->pRight == NULL){free(pNode);return;}free_afterOrder(pNode->pLeft);free_afterOrder(pNode->pRight);free(pNode);}#endif /* BST_H_ */

原创粉丝点击