本题来说http://blog.youkuaiyun.com/v_JULY_v/article/details/6057286 ,中的第十题。
求二叉树中节点的最大距离...
如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
求一棵二叉树中相距最远的两个节点之间的距离。
本文的思路:
cur 记录当前的大小
如果是左子树为空,cur初始化为-1,否则初始化为0
然后采取中序变量的方法。
每个节点遍历的时候会+1, 但是这个节点如果是叶子节点则-1.
代码如下
#include<iostream>
using namespace std;
int maxDis = 0;
int cur = 0;
struct BTree
{
int data;
BTree *pLeft;
BTree *pRight;
};
void middleOrder(BTree *p)
{
if(NULL != p)
{
middleOrder(p->pLeft);
cur++;
if (p->pLeft == NULL && p->pRight == NULL )
{
if ( maxDis < cur )
maxDis = cur;
cur--;
}
cout <<"cur"<<cur<<" data"<<p->data<<endl;
middleOrder(p->pRight);
}
}
int main()
{
BTree a[8];
a[0].pLeft = &a[1];
a[0].pRight = &a[4];
a[0].data = 0;
a[1].pLeft = &a[2];
a[1].pRight = &a[3];
a[1].data = 1;
a[2].pLeft = NULL;
a[2].pRight = NULL;
a[2].data = 2;
a[3].pLeft = NULL;
a[3].pRight = NULL;
a[3].data = 3;
a[4].pLeft = &a[5];
a[4].pRight = &a[6];
a[4].data = 4;
a[5].pLeft = NULL;
a[5].pRight = NULL;
a[5].data = 5;
a[6].pLeft = NULL;
a[6].pRight = &a[7];
a[6].data = 6;
a[7].pLeft = NULL;
a[7].pRight = NULL;
a[7].data = 7;
if (NULL == a->pLeft)
cur = -1;
middleOrder(a);
cout<<maxDis<<endl;
}
另一种思路是根据树的高度去判断。
总长度等于左子树的高度加上右子树的高度。代码先略了。