重建二叉树

来源:互联网 发布:知乎 淘宝办公室零食 编辑:程序博客网 时间:2024/05/21 09:14

已知一棵二叉树的前序遍历和中序遍历结果可以唯一确定一棵二叉树。

题目描述:

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

考察的知识点:

递归、二叉树的三种遍历方式

思路:

比如前序(按根左右的顺序):1,2,4,7,3,5,6,8 中序(按左右根的顺序):4,7,2,1,5,3,8,6
* 第一步:根据前序的结果确定root是1
* 第二步:根据root=1以及中序遍历的结果可知:4,7,2在root的左边,5、3、8、6在root的右边。
* 左右递归:根据前序的2,4,7可知,在root的左子树里面,2是根。 根据中序的4,7,2可以,2没有新的右子树。4、7在2的左边 …

代码:

/** * 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) {        if (pre == null || in == null || pre.length == 0 || in.length == 0) {            return null;        }        int rootValue = pre[0];        TreeNode root = new TreeNode(pre[0]);        root.val = rootValue;        root.left = null;        root.right = null;        int preLength = pre.length;        int inLength = in.length;        // 长度不相等返回空        if (preLength != inLength) {            return null;        }        // 根据rootValue在中序中划分左右子树        int index = -1;        for (int i = 0; i < inLength; i++) {            if (in[i] == rootValue) {                index = i;                break;            }        }        if (index == -1) {            return null;        }        int leftLength = index;        int rightLength = preLength - leftLength - 1;        if (leftLength > 0) {            // 构建左子树            int[] preLeft = new int[leftLength];            System.arraycopy(pre, 1, preLeft, 0, leftLength);            int[] inLeft = new int[leftLength];            System.arraycopy(in, 0, inLeft, 0, leftLength);            root.left = reConstructBinaryTree(preLeft, inLeft);        }        if (leftLength < preLength) {            // 构建右子树            int[] preRight = new int[rightLength];            System.arraycopy(pre, 1 + leftLength, preRight, 0, rightLength);            int[] inRight = new int[rightLength];            System.arraycopy(in, leftLength + 1, inRight, 0, rightLength);            root.right = reConstructBinaryTree(preRight, inRight);        }        return root;    }}
0 0