输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
1)根据前序、中序遍历重建二叉树
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode t = createTree(pre, in, 0, 0, in.length);
return t;
}
public static TreeNode createTree ( int [] pre, int [] in, int i, int low, int high) {
// i 为当前的树根节点在前序遍历数组的位置
// [low, high) 表示当前处理的树所有节点在中序数组中的分布范围
TreeNode t = new TreeNode(pre[i]);
// index 是当前树的根节点在中序遍历数组中的位置
int index = low;
for ( ; index < high; index++ ) {
if ( in[index] == pre[i] )
break;
}
if( index - 1 >= low ) {
t.left = createTree(pre, in, i+1, low, index);
}
else {
t.left = null;
}
if ( index + 1 < high) {
t.right = createTree(pre, in, i + index - low + 1, index + 1, high);
}
else {
t.right = null;
}
return t;
}
}
2) 根据后序遍历和中序遍历重建二叉树,原理差不多
BTree createTree2 ( int *post, int *in, int i, int low, int high ) {
int index;
BTree t = (BTree)malloc(sizeof(BinaryTree));
t->value = post[i];
index = low;
for ( ; index < high; index++ ) {
if ( in[index] == post[i] ) {
break;
}
}
if ( index - 1 >= low ) {
t->leftChild = createTree2(post, in, i - high + index, low, index);
}
else {
t->leftChild = NULL;
}
if ( index + 1 < high ) {
t->rightChild = createTree2(post, in, i - 1, index + 1, high);
}
else {
t->rightChild = NULL;
}
return t;
}
BTree reConstructBTree2 ( int *post, int *in, int n ) {
return createTree2(post, in, n - 1, 0, n);
}