写一个程序求一棵二叉树中相距最远的两个节点之间的距离。
输入要求
输入的第一行包括单独的一个数字T,表示測试序列的数目;
  下面每一行为一个測试序列,測试序列是按先序序列输入字符 ,假设节点没有左或右孩子,则输入用空格表示,最后用一个空格结束一行的输入。
输出要求
 输出二叉树中相距最远的两个节点之间的距离
假如输入
2
ABC  DE G  F    
-+a  *b  -c  d  /e  f   
应当输出
4
6
借鉴了很多代码,最后优deepth()化到最简已经。思路就是遍历每一个节点。空节点为-1,终于的结果肯定是某个节点左子树的深度加上右子树的深度加2,所以求出每一个节点左子树和右子树的深度,取左右子树深度之和加2的最大值就可以。
 
Code:
#include<bits/stdc++.h>
using namespace std;
typedef struct BTree
{
    char data;
    struct BTree *left,*right;
}BTree;
BTree *CreatBTree()
{    
    char ch=getchar();
    if(ch==‘ ‘)
        return NULL;
    BTree *temp=(BTree *)malloc(sizeof(BTree));
    temp->data=ch;
    temp->left=CreatBTree();
    temp->right=CreatBTree();
    return temp;
}
int deepth(BTree *T,int &maxDis)
{
    if(!T)
        return -1;
    int L=deepth(T->left,maxDis);
    int R=deepth(T->right,maxDis);
    maxDis=max(maxDis,L+R+2);
    return max(L,R)+1;
}
void delBTree(BTree *p)
{
    if(p)
    {
        delBTree(p->left);
        delBTree(p->right);
        free(p);
    }
}
int main()
{    
    int t;
    cin>>t;    
    while(t--)
    {    
        getchar();//吃掉回车
        int maxDis=-1;        
        BTree *root=CreatBTree();
        getchar();//吃掉最后结尾的空格
        deepth(root,maxDis);
        cout<<maxDis<<endl;
        delBTree(root);
    }
    return 0;
}原文:http://www.cnblogs.com/ljbguanli/p/7082658.html