题目及测试
package sword006;
/* 重建二叉树
* 问题描述:输入某二叉树的前序遍历和中序遍历结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中
* 都不包含重复的数字。例如输入前序遍历序列:{1,2,4,7,3,5,6,8}和中序遍历{4,7,2,1,5,3,8,6},
* 则重建出图中所示二叉树并且输出它的头结点。
*/
public class main {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
int preOrder[] = { 1, 2, 4, 7, 3, 5, 6, 8 };
int inOrder[] = { 4, 7, 2, 1, 5, 3, 8, 6 };
Solution test = new Solution();
printPreBinaryTree(test.construct(preOrder, inOrder, preOrder.length));
}
// 按照前序遍历打印二叉树的节点
public static void printPreBinaryTree(BinaryTreeNode root) {
if (root == null) {
return;
} else {
System.out.println(root.value + " ");
}
if (root.leftNode != null) {
printPreBinaryTree(root.leftNode);
}
if (root.rightNode != null) {
printPreBinaryTree(root.rightNode);
}
}
}
解法1(成功)
前序 mid,left,right
中序 left,mid,right
1 通过前序的mid,找到中序的mid,因为所有节点值不同,通过hashmap一步找到mid的inIndex
2 找到中序的mid位置,得到left和right的size,从而得到前序里left和right的范围
3 不断循环,left再分成3份,返回left的mid。。。
package sword006;
import java.util.HashMap;
public class Solution {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
public BinaryTreeNode construct(int preOrder[], int inOrder[],
int length) throws Exception {
if (preOrder == null || inOrder == null || length < 0) {
return null;
}
for(int i=0;i<length;i++) {
map.put(inOrder[i], i);
}
return constuctNode(preOrder, inOrder, length, 0, 0);
}
public BinaryTreeNode constuctNode(int preOrder[], int inOrder[],int length,int preFIrst,int inFirst) {
if(length <= 0) {
return null;
}
if(length == 1) {
return new BinaryTreeNode(preOrder[preFIrst]);
}
BinaryTreeNode root = new BinaryTreeNode(preOrder[preFIrst]);
int inIndex = map.get(root.value);
int leftSize = inIndex - inFirst;
int rightSize = length - leftSize - 1;
root.leftNode = constuctNode(preOrder, inOrder, leftSize, preFIrst+1, inFirst);
root.rightNode = constuctNode(preOrder, inOrder, rightSize, preFIrst+leftSize+1, inIndex+1);
return root;
}
}