java中如何实现重建二叉树

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

解法分析:

1.根据前序遍历首节点确定根节点。

2.找到中序遍历中的根节点,确定左子树长度和右子树长度。

3.根据长度,在前序遍历中取左子树前序遍历和右子树前序遍历,在中序遍历中取左子树中序遍历和右子树中序遍历

4.递归左子树和右子树,并将左子树根节点和右子树根节点赋到根节点上。

免费视频教程推荐:java学习

代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre.length == 0 || in.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(pre[0]);
        for(int i = 0 ; i < in.length; i++) {
            if(in[i] == pre[0]) {
                root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));
                root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length)
                ,Arrays.copyOfRange(in,i+1,in.length));
            }
        }
        return root;
    }
}

更多相关文章教程推荐:java编程入门

相关文章

Alt+回车 导入包,自动修正Ctrl+N 查找类Ctrl+Sh...
运行程序出现下面错误:HTTP Status 500 ------------------...
1、建立DM的profile,使用的模版在install_root/profileTempl...
使用dom4j解析XML时,要快速获取某个节点的数据,使用XPath是...
英文操作系统导致 Debug 下的变量查看时显示乱码,可通过改变...
eclipse中javascript报错问题处理:三个地方:&lt;1&...