重构二叉树,java实现,剑指offer原题

来源:互联网 发布:windows server怎么看 编辑:程序博客网 时间:2024/06/06 05:13

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思想:每次从前序遍历中获取根节点,每次从中序遍历中获取左右子树长度一遍在前序遍历中划分左右子树找到相应子树的根节点。过程:一棵树的前序遍历第一个元素必然是根节点,然后根据这个根节点在中序遍历中查找根节点对应位置,获取左右子树长度,得到对应前序遍历中左右子树范围。以左右子树长度是否为0来判断结束。标红字段重点看即可。

package test;


class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
 }
class buildTree{
private int[] pre;
private int[] in;
buildTree(int [] pre,int [] in){
this.pre=pre;
this.in=in;
}
public TreeNode reConstructBinaryTree() {
    TreeNode result = new TreeNode(pre[0]);
    int indexRoot_in=findRoot(result.val);
    int leftLen=indexRoot_in-0;//左子树的长度
    int rightLen=in.length-1-indexRoot_in;//右子树的长度
    ///////
    result.left=constructBinaryTree(leftLen,true,indexRoot_in,0,0,indexRoot_in-1);
    result.right=constructBinaryTree(rightLen,false,indexRoot_in,0+leftLen,indexRoot_in+1,in.length-1);
    return result;
    }
    /*
     * 查找根节点在中序遍历in[]中的位置
     * 
     * */
    public int findRoot(int value){
    int indexOfRoot=-1;
    for(int i=0;i<in.length;i++){
    if(value==in[i])
    indexOfRoot=i;
    }
    return indexOfRoot;
    }
    /* @treelen 子树长度
     * @left 是否为上一根节点的左子树
     * @lastRoot_in 根节点在中序遍历中的位置
     * @Root_pre 根节点在前序遍历中的位置,右子树时作相应变化
     * @start,end 子树在中序遍历中的范围
     * */
    public TreeNode constructBinaryTree(int treeLen,boolean left,int lastRoot_in,int Root_pre,int start,int end) {
    if(treeLen<=0){
    return null;
    }
    TreeNode result=null;
    int index_Root_pre;
    int indexRoot;
    int leftLen;
    int rightLen;
    if(left){
    index_Root_pre=Root_pre+1;
    result = new TreeNode(pre[Root_pre+1]);
    indexRoot=findRoot(result.val);
    leftLen=indexRoot-start;//左子树的长度
    rightLen=end-indexRoot;//右子树的长度
    }
    else{
    index_Root_pre=Root_pre+1;
    result = new TreeNode(pre[index_Root_pre]);
    indexRoot=findRoot(result.val);
    leftLen=indexRoot-start;//左子树的长度
    rightLen=end-indexRoot;//右子树的长度
    }
    result.left=constructBinaryTree(leftLen,true,indexRoot,index_Root_pre,start,indexRoot-1);
    result.right=constructBinaryTree(rightLen,false,indexRoot,index_Root_pre+leftLen,indexRoot+1,end);
    return result;
    }
    
}
public class Solution {

    public static void main(String[] args){
    int [] pre={1,2,4,7,3,5,6,8};
    int [] in={4,7,2,1,5,3,8,6};
    buildTree b=new buildTree(pre,in);
    b.reConstructBinaryTree();
    System.exit(0);
    }
}
阅读全文
0 0