Construct Binary Tree from Preorder and Inorder Traversal

1.已知前序和中序

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

2.已知后序和中序

Given inorder and postorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.


思路:先得到root节点,对左右子树递归。

已知前序和中序或者意志后序和中序,中序是必须要知道的。它的关键点是找到中序的root结点为之,然后两边做递归即可。

1)已知前序和中序:

用递归的方式实现。首先找root节点,前序遍历的第一个节点就是root节点。然后在中序遍历中找到root的位置,之前的是左子树,之后的是右子树。再分别对左子树和右子树做递归。

2)已知后序和中序:

用递归的方式实现。找root节点,它是后序遍历的最后一个节点。在中序遍历中找root的位置,将中序遍历分为左右子树,然后分别做递归即可。

先序:root|左子树|右子树

中序:左子树|root|右子树

后序:左子树|右子树|root

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

typedef struct BinaryTreeNode
{
	char data;
	BinaryTreeNode *leftChild;
	BinaryTreeNode *rightChild;
}Node;

//根据前序和中序来创建二叉树
void makeBinaryTree1(Node **root,char *preOrder,char *midOrder,int length)
{
	if(length == 0)
	{
		(*root) = NULL;
		return;
	}

	(*root) = new Node;
	(*root)->data = *preOrder;

	char *rootplace = strchr(midOrder,(*root)->data);
	if(rootplace == NULL)
	{
		printf("Wrong sample!");
	}

	int leftTreeLength = strlen(midOrder) - strlen(rootplace);
	int rightTreeLength = length - leftTreeLength -1;

	makeBinaryTree1(&(*root)->leftChild,preOrder+1,midOrder,leftTreeLength);
	makeBinaryTree1(&(*root)->rightChild,preOrder+leftTreeLength+1,rootplace+1,rightTreeLength);
}


//根据后序和中序来创建二叉树
void makeBinaryTree2(Node **root,char *postOrder,char *midOrder,int length)
{
	if(length == 0)
	{
		(*root) = NULL;
		return;
	}

	(*root) = new Node;
	(*root)->data = *(postOrder + length -1);

	char *rootplace = strchr(midOrder,(*root)->data);
	if(rootplace == NULL)
	{
		printf("Wrong sample!");
	}

	int leftTreeLength = strlen(midOrder) - strlen(rootplace);
	int rightTreeLength = length - leftTreeLength -1;

	makeBinaryTree2(&(*root)->leftChild,postOrder,midOrder,leftTreeLength);
	makeBinaryTree2(&(*root)->rightChild,postOrder+leftTreeLength,midOrder+leftTreeLength+1,rightTreeLength);
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值