二叉树-----求深度

1.递归方法:分别计算出左子树、右子树的深度,最后取较大者+1即是二叉树深度。

typedef struct BinaryTree
{
	int data;
	struct BinaryTree *Left;
	struct BinaryTree *Right;
	struct BinaryTree *Parent;
}Node;

//递归求二叉树深度
int PostTreeDepth(BinaryTree* root)
{
	int leftdepth, rightdepth, max;
	if (root != NULL)
	{
		leftdepth = PostTreeDepth(root->Left);
		rightdepth = PostTreeDepth(root->Right);
		max = leftdepth > rightdepth ? leftdepth : rightdepth;
		return (max + 1);
	}
	else
		return 0;
}

2.非递归方法:用双向队列的大小达到的最大值减去1等于二叉树的深度

int GetMax(int a, int b)
{
	return a > b ? a : b;
}

int GetTreeHeightPostorder(const BTree root)
{
	struct Info
	{
		int level;
		const BTree TreeNode;
	};
//利用双向队列存储右子树的结点和深度
	deque<Info> dq;
	int TreeHeight = -1;
	int level = -1;
	while (1)
	{
//分别算出左右子树的深度
		while (root)
		{
			++level;
			if (root->right)
			{
				Info info = { root->right,level };
				dq.push_back(info);
			}
			root = root->left;
		}
//得出最大的深度
		TreeHeight = GetMax(TreeHeight, level);
//当队列中的右子树结点遍历完后,队列为空,结束循环
		if (dq.empty())
			break;
//否则取队列中最后一个结点和它的深度,并弹出该结点
		const Info& info = dq.back();
		root = info.TreeNode;
		level = info.level;
		dq.pop_back();
	}
	return TreeHeight;
}

3.对方法二的优化:在往双向列表放入元素后(或者在访问结点数据时),辅助栈的栈大小达到最大值

int GetMax(int a, int b)
{
	return a > b ? a : b;
}

int GetTreeHeightPostorder(const BTree root)
{
//创建双向队列
	deque<const BTree> dq;
	int TreeHeight = -1;
	while (1)
	{
//遍历左子树,并把遍历过的结点存入队列中
		for (;root != NULL;root = root->left)
			dq.push_back(root);
//求出当前树深度和队列长度减1的较大值
		TreeHeight = GetMax(TreeHeight, (int)dq.size() - 1);
		while (1)
		{
//当队列为空时,表示遍历完,返回树的深度
			if (dq.empty())
				return TreeHeight;
//取队列最后一个结点为父结点
			const BTree parent = dq.back();
			const BTree Rchild = parent->right;
//当该父结点存在且不当与当前当前结点,则退出循环并以右孩子结点为新的当前结点
			if (Rchild && root != Rchild)
			{
				root = Rchild;
				break;
			}
//否则把父结点作为当前结点,并把该父结点即队列最后一个结点弹出队列
			root = parent;
			dq.pop_back();
		}
	}
//最后再返回树的深度
	return TreeHeight;
}

猜你喜欢

转载自blog.csdn.net/weixin_39916039/article/details/81774522