题目:
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
知识点:
- 树的基本知识,value、左右子节点;
注意:
无
代码实现:
- 递归思想(暂时没有彻底理解,背写!!!)
public class Num07wang {
public static void main(String[] args) {
int preorder[] = {1, 2, 4, 7, 3, 5, 6, 8};
int inorder[] = {4, 7, 2, 1, 5, 3, 8, 6};
TreeNode treeNode = rebuildBinaryTree(preorder, inorder);
System.out.println(treeNode);
}
/**
* 重构二叉树
* @param preorder
* @param inorder
* @return
*/
private static TreeNode rebuildBinaryTree(int[] preorder, int[] inorder) {
if (preorder==null || inorder == null) {
return null;
}
//核心算法
TreeNode node = rebuildBinaryTreeCore(preorder, 0, preorder.length-1, inorder, 0,
inorder.length-1);
return node;
}
/**
* 核心算法
* @param preorder
* @param i:前序初始index
* @param j:前序终止index
* @param inorder
* @param k:中序初始index
* @param l:中序终止index
*/
private static TreeNode rebuildBinaryTreeCore(int[] preorder, int preStartIndex, int preEndIndex
, int[] inorder, int inStartIndex, int inEndIndex) {
if(preStartIndex>preEndIndex || inStartIndex>inEndIndex) {
return null;
}
//根据前序确定根节点
TreeNode node = new TreeNode(preorder[preStartIndex]);
//定位根节点再中序中的位置
for(int i=inStartIndex; i<=inEndIndex; i++) {
if(preorder[preStartIndex] ==inorder[i]) {
//(i- inStartIndex)为中序排列中左子树的个数
//左子树
node.left = rebuildBinaryTreeCore(preorder, preStartIndex+1, preStartIndex+ (i-inStartIndex)
, inorder, inStartIndex, i-1);
//右子树
node.right = rebuildBinaryTreeCore(preorder, preStartIndex+1+(i-inStartIndex), preEndIndex, inorder, i+1, inEndIndex);
}
}
return node;
}
public static class TreeNode{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data) {
this.data = data;
}
public String toString() {
return "TreeNode [data=" + data + ", left=" + left + ", right=" + right
+ "]";
}
}
}