*
* 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) {
TreeNode root = reConstructTreecode(
pre,0,pre.length-1,in,0,in.length-1);
return root;
}
public static TreeNode reConstructTreecode(
int[] pre,int startpre,int endpre,int[] in,int startin,int endin){
if(startpre>endpre||startin>endin)
return null;
TreeNode root = new TreeNode(pre[startpre]);
for(int i=startin;i<=endin;i++){
if(in[i]==pre[startpre]){
root.left=reConstructTreecode(pre,startpre+1,startpre+i-startin,in,startin,i-1);
root.right=reConstructTreecode(pre,startpre+i-startin+1,endpre,in,i+1,endin);
}
}
return root;
}
}
【剑指offer】7.重建二叉树
最新推荐文章于 2023-02-20 10:29:14 发布