码迷,mamicode.com
首页 > 编程语言 > 详细

数据结构 - 求二叉树中结点的最大距离(C++)

时间:2016-03-28 13:39:57      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

// ------BTreeMaxNodeLength.cpp------

#include <iostream>

using namespace std;

template <class T>
struct BTNode
{
	// 左孩子
	BTNode<T> *lChild;
	// 右孩子
	BTNode<T> *rChild;
	// 该结点的值
	T data;
	// 左子树最长距离
	int leftSubTreeMaxLength;
	// 右子树最长距离
	int rightSubTreeMaxLength;
};

template <class T>
class BinaryTree
{
public:
	void GetMaxNodeLength(BTNode<T> * root, int *maxNodeLength)
	{
		// 遍历到叶子结点,返回
		if (root == NULL)
		{
			return;
		}

		// 假设左子树为空,那么该结点左子树最长距离为0
		if (root->lChild == NULL)
		{
			root->leftSubTreeMaxLength = 0;
		}

		// 假设右子树为空,那么该结点右子树最长距离为0
		if (root->rChild == NULL)
		{
			root->rightSubTreeMaxLength = 0;
		}

		// 假设左子树不为空,递归查找左子树最长距离
		if (root->lChild != NULL)
		{
			GetMaxNodeLength(root->lChild, maxNodeLength);
		}

		// 假设右子树不为空,递归查找右子树最长距离
		if (root->rChild != NULL)
		{
			GetMaxNodeLength(root->rChild, maxNodeLength);
		}

		// 计算左子树中距离根结点的最长距离
		if (root->lChild != NULL)
		{
			if (root->lChild->leftSubTreeMaxLength > root->lChild->rightSubTreeMaxLength)
			{
				root->leftSubTreeMaxLength = root->lChild->leftSubTreeMaxLength + 1;
			}
			else
			{
				root->leftSubTreeMaxLength = root->lChild->rightSubTreeMaxLength + 1;
			}
		}

		// 计算右子树中距离根结点的最长距离
		if (root->rChild != NULL)
		{
			if (root->rChild->leftSubTreeMaxLength > root->rChild->rightSubTreeMaxLength)
			{
				root->rightSubTreeMaxLength = root->rChild->leftSubTreeMaxLength + 1;
			}
			else
			{
				root->rightSubTreeMaxLength = root->rChild->rightSubTreeMaxLength + 1;
			}
		}

		// 更新最长距离
		if (root->leftSubTreeMaxLength + root->rightSubTreeMaxLength > *maxNodeLength)
		{
			*maxNodeLength = root->leftSubTreeMaxLength + root->rightSubTreeMaxLength;
		}
	}
};

数据结构 - 求二叉树中结点的最大距离(C++)

标签:

原文地址:http://www.cnblogs.com/bhlsheji/p/5328600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!