计算二叉树的任意两节点的最远距离。

来源:互联网 发布:收音机软件哪个好 编辑:程序博客网 时间:2024/04/30 17:49

利用计算二叉树高度的方法计算两个节点最远距离。

计算出一个节点的深度,左右子树的深度,然后加起来,就是这个节点的最远的距离了。然后遍历二叉树的所以的节点,找出最大的节点即可。

#include <iostream>using namespace std;typedef struct BtreeNode{int data;struct BtreeNode *left,*right;}node;void create(node *&r ,int m){if(r==NULL){node *t = new node();t->data = m;t->left =NULL;t->right = NULL;r = t;}else{if(m<r->data){create(r->left ,m);}else{create(r->right ,m);}}}int getdepth(node *r){if(r==NULL){return 0;}else{int max = getdepth(r->left);if(getdepth(r->right)>max){max = getdepth(r->right);}return (max+1);}}int maxlen=0;void Find(node *r){int ldis ,rdis ;if(r==NULL){return;}if(r->left ){       ldis = getdepth(r->left);}if(r->right){rdis = getdepth(r->right);}if(ldis+rdis>maxlen){maxlen = ldis +rdis;}Find(r->left);Find(r->right);}void main(){node *root=NULL;create(root,10);create(root,6);create(root,4);create(root,8);create(root,15);create(root,14);create(root,13);create(root,12);create(root,11);create(root,16);create(root,18);create(root,19);create(root,20);create(root,21);    cout<<"深度:"<<getdepth(root)<<endl;Find(root);cout<<"最大距离"<<maxlen<<endl;}


 

原创粉丝点击