(剑指offer)重建二叉树

来源:互联网 发布:信用卡网络推广合作 编辑:程序博客网 时间:2024/05/17 18:43

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

代码如下:

public class ReConstructBinaryTree {    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {        TreeNode root = null;        if (pre == null || in == null) {            return null;        }        root = constructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);        return root;    }    public TreeNode constructBinaryTree(int[] pre, int preStr, int preEnd, int[] in, int inStr, int inEnd) {        if (preStr > preEnd || inStr > inEnd) {            return null;            }        // 前序遍历的第一个结点为二叉树的根节点        TreeNode root = new TreeNode(pre[preStr]);        // 记录每次根节点所在位置        int index = 0;        for (; index < inEnd; index++) {            if (in[index] == pre[preStr]) {                break;            }        }        // 递归调用求得根节点的左子树        root.left = constructBinaryTree(pre, preStr + 1, preStr + index - inStr,                 in, inStr, index - 1);        // 递归调用求得根节点的右子树        root.right = constructBinaryTree(pre, preStr + index - inStr + 1, preEnd,                 in, index + 1, inEnd);        return root;    }}
原创粉丝点击