题目: 输入一颗二叉树先序遍历的字符串,输出该二叉树的最大叶子节点距离
分析知,最大的距离要么是经过根节点的一条路径,要么是在左子树中的一条路径,或者是在右子树中的一条路径。
那么可以知道最大叶子节点的距离是左右子树的高度和、左子树最大叶节点距离、右子树最大叶节点距离中的最大值。
可以摒弃前面的用全局变量记录最大叶节点距离的方法(不可重入),代码如下。
#include<iostream>
using namespace std;
//树节点类型定义
struct BTNode
{
char value;
BTNode* left;
BTNode* right;
BTNode(char k):value(k),left(NULL),right(NULL){}
};
//三个数中取最大值
int Max(int a,int b,int c)
{
int tmp = a>b?a:b;
return tmp>c?tmp:c;
}
//求树的高度
int TreeHeight(BTNode* root)
{
if(root == NULL)
return -1;
int ldepth = TreeHeight(root->left);
int rdepth = TreeHeight(root->right);
return ldepth>rdepth?ldepth+1:rdepth+1;
}
//求经过根节点的最大两个节点的距离
int LenViaRoot(BTNode* root)
{
if(root == NULL)
return 0;
int leftLen = TreeHeight(root->left);
int rightLen = TreeHeight(root->right);
return leftLen + rightLen + 2;
}
//主调函数,求二叉树中两个叶节点的最大距离
int maxLeafLen(BTNode* root)
{
if(root == NULL)
return 0;
return Max(LenViaRoot(root),maxLeafLen(root->left),maxLeafLen(root->right));
}
//按先序遍历的顺序输入字符串构造一颗二叉树
void createBTree(BTNode*& root)
{
char val = getchar();
if(val == '#')
{
root = NULL;
return;
}
else
{
root = new BTNode(val);
createBTree(root->left);
createBTree(root->right);
}
}
//后序遍历的方式输出二叉树以验证上面的先序遍历顺序建立的二叉树的正确性
void postOrderRecursive(BTNode* root)
{
if(root != NULL)
{
postOrderRecursive(root->left);
postOrderRecursive(root->right);
cout<<root->value<<" ";
}
}
int main()
{
BTNode* root = NULL;
cout<<"请按先序遍历的方式输入一颗二叉树节点序列,#代表空节点: ";
createBTree(root);
cout<<"构造的二叉树的后序遍历为: ";
postOrderRecursive(root);
cout<<endl;
cout<<"二叉树中最大叶节点距离: "<<maxLeafLen(root)<<endl;
return 0;
}