
思路:
实现:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length==0 || in.length==0){
return null;
}
TreeNode node=new TreeNode(pre[0]);
for(int i=0;i<in.length;i++){
if(pre[0]==in[i]){
node.left=reConstructBinaryTree(Arrays.copyOfRange(pre,i,i+1),Arrays.copyOfRange(in,0,i));
node.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,in+1,in.length));
}
}
return node;
}
}
本文介绍了一种使用前序和中序遍历数组重构二叉树的算法。通过递归方式找到根节点,并根据中序遍历确定左右子树,进而完成整棵树的重建。
246

被折叠的 条评论
为什么被折叠?



