重建二叉树 (剑指offer第六题)

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

/**
 * 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) {
        TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
        return root;
    }
    public TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn){
        if(startPre>endPre||startIn>endIn){
            return null;
        }
        TreeNode root=new TreeNode(pre[startPre]);
        for (int i=0;i<=endIn;i++){
            if(root.val==in[i]){
                root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
                root.right=reConstructBinaryTree(pre,startPre+1+i-startIn,endPre,in,i+1,endIn);
                break;
            }
        }
        return root;
    }
}

有思路,但是没写出来。还得多练练。

解释一下大神的几个关键点:

创建左子树时:startPre+i-startIn

其中i-startIn表示的是有几个左孩子。

创建右子树时:i-startIn+startPre+1

其中i-startIn同上。+1代表的是根。前序遍历去掉左孩子和根就是右孩子开始算的地方。

大神的思路简洁。这个代码风格值得学习。加油。

最后还有个问题,留着以后解决: TreeNode root=new TreeNode(pre[startPre]);

搞不懂为什么这句会在eclipse中报错,但在牛客测试中没报错。

苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
原文地址:https://www.cnblogs.com/shaer/p/10247061.html