“中序遍历"和”后序遍历“重建二叉树

比较简单,主要是分治的思路。

           5

          / \

        3     8

      /  \    /

   2     4  6

贴上代码:

#include <iostream>

using namespace std;

struct TreeNode
{
	int value;
	TreeNode *pLeft;
	TreeNode *pRight;
};

int findRoot(int *postOrder,int beginP,int endP){
	if(beginP>endP){
		return NULL;
	}
	return postOrder[endP];
}

int findIndexOfRoot(int *inOrder,int beginI,int endI,int root){
	if(beginI>endI){
		return NULL;
	}
	for(int i = beginI;i <= endI;i++){
		if(inOrder[i] == root){
			return i;
		}
	}
}

TreeNode* createTree(int *inOrder,int beginI,int endI,int *postOrder,int beginP,int endP){
	if(beginI>endI){
		return NULL;
	}
	if(beginP>endP){
		return NULL;
	}
	int root = findRoot(postOrder,beginP,endP);
	int pIndex = findIndexOfRoot(inOrder,beginI,endI,root);
	int leftNum = pIndex - beginI;//左子树有多少个节点
	TreeNode *pNew = new TreeNode;
	pNew->value = root;
	pNew->pLeft = NULL;
	pNew->pRight = NULL;
	pNew->pLeft = createTree(inOrder,beginI,pIndex-1,postOrder,beginP,beginP+leftNum-1);
	pNew->pRight = createTree(inOrder,pIndex+1,endI,postOrder,beginP+leftNum,endP-1);
	return pNew;
}

void preOrder(TreeNode *pRoot){
	if(pRoot != NULL){
		cout << pRoot->value << " ";
		preOrder(pRoot->pLeft);
		preOrder(pRoot->pRight);
	}
}
int main(){
	int inOrder[] = {2,3,4,5,6,8};
	int postOrder[] = {2,4,3,6,8,5};
	TreeNode *pRoot = createTree(inOrder,0,5,postOrder,0,5);
	preOrder(pRoot);
	cout << endl;
}

你可能感兴趣的:(“中序遍历"和”后序遍历“重建二叉树)