題目格式: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; } }