题目格式:java
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.Arrays; public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { } }
解题思路:数组
这道题主要是须要利用前序遍历和中序遍历的特色,提及来比较麻烦,仍是直接举例比较清除。网络
这里的前序遍历是12473568,中序遍历是47215386spa
以下图所示。咱们在前序遍历中找到根节点,在中序遍历中利用根节点找到它的左子树和右子树code
(图片来源于网络)blog
再形象一点,咱们把它画成一棵树的形状图片
如今咱们再把247这一组数按照刚才的步骤来一遍就能够获得1的左子树。it
前序遍历:2 4 7io
中序遍历:4 7 2class
仍是按照刚才的方法,就能够获得这棵树的根节点是2,左子树是四、 7,右子树为空
就这样一直构建下去咱们就能够获得一棵完整的二叉树。
解题代码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.Arrays; public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre == null) return null; return reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1); } public TreeNode reConstructBinaryTree(int[] pre,int preStart, int preEnd,int[] in, int inStart, int inEnd) { if(preStart > preEnd || inStart > inEnd) { return null; } int rootVal = pre[preStart]; // 前序数组的第一个元素是树的根节点 int inRootIndex = 0 ; // 中序数组中根节点的位置 TreeNode root = new TreeNode(rootVal); //寻找中序数组中根节点的位置 for(int i = inStart; i <= inEnd; i++) { if( in[i] == rootVal ) { inRootIndex = i; break; } } //构建左子树 root.left = reConstructBinaryTree(pre, preStart + 1, preStart + inRootIndex - inStart, in, inStart, inRootIndex - 1); //构建右子树 root.right = reConstructBinaryTree(pre,preStart + 1 + inRootIndex - inStart,preEnd, in, inRootIndex + 1, inEnd); return root; } }