关于二叉树,建立、遍历、求节点最大距离

本文介绍了如何建立二叉树并进行深度遍历,动态规划求解二叉树节点的最大距离。通过深度遍历计算左右子树叶子节点到根节点的距离,再结合层次遍历,找出经过根节点的最大距离。
         今天做了一题求二叉树节点的最大距离,顺便写了下二叉树的建立,遍历的过程。
  我觉得这题的主要思想是深度遍历+动态规划,我们在深度遍历的过程中,对于某一个子树,求出左右子树叶子节点到根节点的最大距离,进而求出经过根节点的最大距离。 最后求出所有子树经过根节点的最大距离。就是这个题目的最终结果。代码如下:
 
//二叉树的建立,以及遍历
//16 14 8 2 -1 -1 4 -1 -1 7 1 -1 -1 -1 10 9 -1 -1 3 -1 -1
//16 14 8 2 -1 -1 4 -1 -1 7 1 -1 -1 -1 -1
void  BuildBTree(BTreeNode* &pRoot)
{
	int nTemp;
	cin >> nTemp;
	if (nTemp == -1)
	{
		pRoot = NULL;
	}
	else
	{
		pRoot = new BTreeNode();
		pRoot->nValue = nTemp;

		BuildBTree(pRoot->pLeft);
		BuildBTree(pRoot->pRight);
	}
}

void PreOrderBTree(BTreeNode* pRoot)
{
	if (pRoot == NULL)
	{
		return;
	}

	cout << pRoot->nValue << " ";
	PreOrderBTree(pRoot->pLeft);
	PreOrderBTree(pRoot->pRight);
}

void MidOrderBTree(BTreeNode* pRoot)
{
	if (pRoot == NULL)
	{
		return;
	}
	MidOrderBTree(pRoot->pLeft);
	cout << pRoot->nValue << " ";
	MidOrderBTree(pRoot->pRight);
}

void PostOrderBTree(BTreeNode* pRoot)
{
	if (pRoot == NULL)
	{
		return;
	}
	PostOrderBTree(pRoot->pLeft);
	PostOrderBTree(pRoot->pRight);
	cout << pRoot->nValue << " ";
}

//层次遍历 也就是广度优先遍历
void VisitByLevel(BTreeNode* pRoot)
{
	if (pRoot == NULL)
	{
		return;
	}

	queue<BTreeNode*> treeQueue;
	treeQueue.push(pRoot);


	while(!treeQueue.empty())
	{
		BTreeNode* pNode = treeQueue.front();
		cout << pNode->nValue  << " ";
		treeQueue.pop();
		if (pNode->pLeft != NULL)
		{
			treeQueue.push(pNode->pLeft);
		}

		if (pNode->pRight != NULL)
		{
			treeQueue.push(pNode->pRight);
		}
	}
}

int  GetMaxNodeMaxDistance(BTreeNode* pRoot)
{
	if (pRoot == NULL)
	{
		return -1;
	}

	//左子树叶子结点到根结点的最大距离
	int max_left_distance = GetMaxNodeMaxDistance(pRoot->pLeft);
	//右子树叶子结点到根结点的最大距离
	int max_right_distance = GetMaxNodeMaxDistance(pRoot->pRight);
	//每个子树节点的最大距离
	int max_root_distance = max_left_distance + max_right_distance + 2;
	//比较每个子树节点的最大距离
	if (max_root_distance > max_distance)
	{
		max_distance = max_root_distance;
	}

	return max_left_distance > max_right_distance ? max_left_distance+1 : max_right_distance+1;
}

int max_distance = 0;
int main()
{

	BTreeNode* Root = NULL;
	BuildBTree(Root);

	cout << "----------------Build End------------------" << endl;
	system("pause");
	cout << "PreOrderBTree:" << endl;
	PreOrderBTree(Root);
	cout << endl << "MidOrderBTree:" << endl;
	MidOrderBTree(Root);
	cout << endl << "PostOrderBTree:" << endl;
	PostOrderBTree(Root);
	cout << endl << "VisitByLevel:" << endl;
	VisitByLevel(Root);
	cout << endl << "GetMaxNodeMaxDistance:" << endl;
	GetMaxNodeMaxDistance(Root);
	cout << max_distance << endl;
	system("pause");
        return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值