輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹,
假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字,
例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹并回傳,
根據二叉樹前序遍歷第一個元素就是root,中序遍歷root左邊的是左子樹元素,root右邊是右子樹元素
即第一確定root元素在中序遍歷中的位置,即可確定左右子樹范圍
/**
* 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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/270771.html
標籤:其他
上一篇:資料結構亂扯
