劍指offer[重建二叉樹]
阿新 • • 發佈:2018-11-24
劍指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) {
if (pre.length<=0||in.length<= 0) {
return null;
}
TreeNode treeNode=new TreeNode(pre[0]);
int rootIndex=0;
for(int i=0;i<in.length;i++){
if(in[i]==pre[0]){
rootIndex=i;
}
}
int []preLeft=new int[rootIndex];
int []preRight=new int[pre.length- rootIndex-1];
int []inLeft=new int[rootIndex];
int []inRight=new int[in.length-rootIndex-1];
for(int i=0;i<rootIndex;i++){
preLeft[i]=pre[i+1];
inLeft[i]=in[i];
}
for(int i=0;i<in.length-rootIndex-1;i++){
preRight[i]=pre[rootIndex+1+i];
inRight[i]=in[rootIndex+1+i];
}
treeNode.left=reConstructBinaryTree(preLeft,inLeft);
treeNode.right= reConstructBinaryTree(preRight,inRight);
return treeNode;
}
}