如果我们把二叉树看成一个图,
父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
求一棵二叉树中相距最远的两个节点之间的距离。
#include "stdlib.h"
#include "stdio.h"
typedef struct BTNode
{
int data;
struct BTNode *lnode;
struct BTNode *rnode;
}BTNode;
BTNode *CreateTree(int pre[], int in[], int l1, int r1, int l2, int r2){
BTNode *s;
int i;
if(l1 > r1)
return NULL;
s = (BTNode *)malloc(sizeof(BTNode));
s->lnode = s->rnode = NULL;
for(i=l2; i<=r2; ++i){
if(pre[l1] == in[i]){
break;
}
}
s->data = in[i];
s->lnode = CreateTree(pre, in, l1+1, l1+i-l2, l2, i-1);
s->rnode = CreateTree(pre, in, l1+i-l2+1, r1, i+1, r2);
return s;
}
void PrePrint(BTNode *p){
if(p != NULL){
printf("%d ", p->data);
PrePrint(p->lnode);
PrePrint(p->rnode);
}
}
void InPrint(BTNode *p){
if(p != NULL){
InPrint(p->lnode);
printf("%d ", p->data);
InPrint(p->rnode);
}
}
void FindDepth(BTNode *p, int depth, int &maxDepth){
if(p != NULL){
++depth;
printf("current depth = %d\n", depth);
//if depth bigger than maxDepth;
if(depth > maxDepth){
maxDepth = depth;
}
FindDepth(p->lnode, depth, maxDepth);
FindDepth(p->rnode, depth, maxDepth);
--depth;
}
}
void main(){
int pre[] = {10, 5, 4, 7, 12, 8, 11, 6};
int in[] = {4, 5, 12, 7, 10, 11, 8, 6};
BTNode *p;
p = CreateTree(pre, in, 0, 7, 0, 7);
int depth = 0;
int maxDepth = 0;
FindDepth(p, depth, maxDepth);
printf("maxDepth = %d\n", maxDepth);
}