二叉树-----已知先序遍历、中序遍历,求后序遍历

步骤:

1.确定树的根结点:树根是在先序遍历中最先出现的元素,即先序遍历的第一个结点是二叉树的根。

2.求解树的子树:找到根在中序遍历的位置,位置左边是二叉树的左孩子,右边是右孩子,若根结点的左边或右边为空,则该方向子树为空;若左右子树都为空,则该结点是叶子节点。

3.对二叉树的左右孩子分别进行步骤1,2,直到求出二叉树结构为止。

int InitTree(Node* Root, char *front, char *middle, int len)
{
	int i = 0;
	Root->data = front[0];
	if (len == 0)
		return 0;
//找到根结点在中序遍历的位置
	for (i = 0;i < len;++i)
	{
		if (middle[i] == Root->data)
			break;
	}
//如果Root存在左孩子
	if (i != 0)
	{
		Root->left = new struct BinaryTree;
		InitTree(Root->left, front + 1, middle, i);
	}
//如果Root存在右孩子
	if (i != len - 1)
	{
		Root->right = new struct BinaryTree;
		InitTree(Root->right, front + i + 1, middle + i + 1, i);
	}
	return 1;
}

猜你喜欢

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