《编程之美》第3.8节:求二叉树中的最大距离
问题:如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,我们定义距离为两个节点之间的边数,求一棵二叉树中县局最远的两个节点之间的距离。
解法:树的后序遍历,然后再每个节点中维护两个变量nMaxLeft,nMaxRight保存当前节点为根节点的子树中的最远距离,不断更新maxLength,直到根节点。
代码:
#include<iostream>
using namespace std;
struct Node
{
Node *left;
Node *right;
int nMaxLeft;
int nMaxRight;
char value;
Node(char v,Node *l=nullptr,Node *r=nullptr,int nl=0,int nr=0):value(v),left(l),right(r),nMaxLeft(nl),nMaxRight(nr){}
};
void findMaxLength(Node *root,int &maxLength)
{
if(root->left==nullptr)
root->nMaxLeft=0;
else
{
findMaxLength(root->left,maxLength);
root->nMaxLeft=max(root->left->nMaxLeft,root->left->nMaxRight)+1;
}
if(root->right==nullptr)
root->nMaxRight=0;
else
{
findMaxLength(root->right,maxLength);
root->nMaxRight=max(root->right->nMaxLeft,root->right->nMaxRight)+1;
}
if(maxLength<root->nMaxLeft+root->nMaxRight)
maxLength=root->nMaxLeft+root->nMaxRight;
}
int main()
{
Node *root=new Node('A');
root->left=new Node('B');
root->left->left=new Node('C');
root->left->right=new Node('D');
root->left->left->left=new Node('E');
root->left->right->left=new Node('J');
root->right=new Node('F');
/* root->right->left=new Node('G');
root->right->right=new Node('H');
root->right->left->right=new Node('I');*/
int result=0;
findMaxLength(root,result);
cout<<result<<endl;
system("pause");
return 0;
}