求二叉树中节点的最大距离

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值