【剑指Offer】重建二叉树 解题报告

来源:互联网 发布:mac flash player 编辑:程序博客网 时间:2024/04/27 02:15

【剑指Offer】重建二叉树 解题报告

标签(空格分隔): 剑指Offer


题目地址:https://www.nowcoder.com/ta/coding-interviews

题目描述:

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

Ways

这个题和之前的C++版本一样,换个方式重新写了一遍。最最重要的部分是计算两个数组的左右起点终点。

参考:http://blog.csdn.net/fuxuemingzhu/article/details/60145697

/** * 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) {        return build(pre, in, 0, pre.length - 1, 0, in.length - 1);    }    public TreeNode build(int [] pre,int [] in, int s1, int e1, int s2, int e2){        TreeNode node = new TreeNode(pre[s1]);        int rootIndx = 0;        for(int i = s2; i <= e2; i++){            if(pre[s1] == in[i]){                rootIndx = i;                break;            }        }        if(rootIndx != s2){            node.left = build(pre, in, s1 + 1, s1 + (rootIndx - s2), s2, rootIndx - 1);        }        if(rootIndx != e2){            node.right = build(pre, in, s1 + (rootIndx - s2) + 1, e1, rootIndx + 1, e2);        }        return node;    }}

Date

2017 年 4 月 20 日

0 0