輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。
假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。
例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
根據二叉樹前序遍歷第一個元素就是root,中序遍歷root左邊的是左子樹元素,root右邊是右子樹元素
即第一肯定root元素在中序遍歷中的位置,便可肯定左右子樹範圍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) { if(pre.length==0)return null; int rootVal=pre[0]; if(pre.length==1) return new TreeNode(rootVal); //先找到root所在的位置,肯定好前序和中序中左子樹和右子樹序列的範圍 TreeNode root=new TreeNode(rootVal); int rootIndex=0; for(int i=0;i<in.length;i++){ if(rootVal==in[i]){ rootIndex=i; break; } } root.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,rootIndex+1),Arrays.copyOfRange(in,0,rootIndex)); root.right=reConstructBinaryTree(Arrays.copyOfRange(pre,rootIndex+1,pre.length),Arrays.copyOfRange(in,rootIndex+1,in.length)); return root; } }