#include <iostream>
using namespace std;
//二叉树结构
typedef struct BinaryTreeNode
{
char m_chValue;
BinaryTreeNode *m_pLChild;
BinaryTreeNode *m_pRChild;
}BiTree;
//求树的深度
int depth(BiTree *T)
{
if(!T)
{
return 0; //判断当前结点是否为叶子结点
}
int d1= depth(T->m_pLChild); //求当前结点的左孩子树的深度
int d2= depth(T->m_pRChild); //求当前结点的右孩子树的深度
return (d1 > d2 ? d1 : d2) + 1;
}
//最大距离 = 左子树深度 + 右子树深度
int MaxDistance(BiTree *root)
{
if (NULL == root)
{
return 0;
}
int nLDeep = depth(root->m_pLChild);//左子树深度
int nRDeep = depth(root->m_pRChild);//右子树深度
int sum = nLDeep + nRDeep;
return sum;
}
//创建二叉树
BiTree *CreateBiTree(BiTree *pTree = NULL)
{
char ch;
cin>>ch;
if ('#' == ch)
{
pTree = NULL;
}
else
{
pTree = new BiTree;
pTree->m_chValue = ch;
pTree->m_pLChild = CreateBiTree(pTree->m_pLChild);
pTree->m_pRChild = CreateBiTree(pTree->m_pRChild);
}
return pTree;
}
//遍历二叉树
void TraverseTree(BiTree *root)
{
if (NULL != root)
{
cout<<root->m_chValue<<endl;
TraverseTree(root->m_pLChild);
TraverseTree(root->m_pRChild);
}
}
int main()
{
BiTree *root = NULL;
root = CreateBiTree();
int deep = MaxDistance(root);
cout<<deep<<endl;
// TraverseTree(root);
return 1;
}
求二叉树中节点的最大距离
最新推荐文章于 2019-06-09 16:06:59 发布