编程语言
首页 > 编程语言> > Java解决重建二叉树算法题

Java解决重建二叉树算法题

作者:互联网

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

解题思路

由二叉树的前序遍历序列可知,1 为二叉树的根节点。由二叉树的中序遍历序列可知,1之前的结点,即4、7、2为其左子树的中序遍历序列,1之后的结点 5、3、8、6为其右子树的中序遍历序列。因此,左子树共有三个节点,右子树有4个结点。所以,在前序遍历序列中,1结点后的三个结点就是左子树三个结点的值,最后的四个结点就是右子树的四个结点的值。
这样,我们就分别找到了二叉树的根节点,左、右子树的前序和中序遍历序列,因此可以使用递归的方法去完成问题。

JAVA代码

/**
 * 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) throws Exception{
        if(pre==null||in==null||pre.length!=in.length){
            return null;
        }
        return ConstructCore(pre,0,pre.length-1,in,0,in.length-1);
    }
    
    public TreeNode ConstructCore(int[] pre,int preStart,int preEnd,
                            int[] in,int inStart,int inEnd) throws Exception{
        int rootVal = pre[preStart];
        TreeNode root = new TreeNode(rootVal);
        if(preStart == preEnd){
            if(inStart == inEnd && pre[preStart] == in[inStart]){
                return root;
            }else{
                throw new Exception("Invalid input data");
            }
        }
        //在中序遍历中找到根节点的值
        int inRoot = inStart;
        while(inRoot < inEnd && in[inRoot] != rootVal){
            inRoot++;
        }
        if(inRoot==inEnd && in[inRoot]!=rootVal){
            throw new Exception("Invalid input data");
        }
        int leftLength = inRoot - inStart;
        int rightLength = inEnd - inRoot;
        if(leftLength>0){
            root.left = ConstructCore(pre,preStart+1,preStart+leftLength,in,inStart,inRoot-1);
        }
        if(rightLength>0){
            root.right = ConstructCore(pre,preStart+leftLength+1,preEnd,in,inRoot+1,inEnd);
        }
        return root;
    }
}

标签:pre,遍历,Java,int,中序,算法,二叉树,inRoot
来源: https://blog.csdn.net/qq_41216255/article/details/100120707