思路迭代
- 自己想的笨方法:从前序遍历入手,一个一个分析,结合中序里的情况,虽然笨,但是还是有效。
- 别人的好方法:一句话表达,子树的根节点就是树的左右节点
代码展示
笨办法
public class Solution {
public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
Boolean flag = true;
int int_pre,int_pro;
TreeNode tree_pre,tree_pro;
TreeNode first = new TreeNode(pre[0]);
int first_loc = loc(pre[0],in);
int len = pre.length;
TreeNode tmp_1= null,tmp_2= null;
int in_loc_1=0,in_loc_2=0;
for (int i =1;i< len ; i++){
if (i == 1){
tmp_1 = first;
in_loc_1 = first_loc;
}
int pre_val = pre[i];
if (i%2 == 0){
tmp_1 = new TreeNode(pre_val);
in_loc_1 = loc(pre_val,in);
flag = true;
}
else {
tmp_2 = new TreeNode(pre_val);
in_loc_2 = loc(pre_val,in);
flag = false;
}
if (flag){
int_pre = in_loc_2;
int_pro = in_loc_1;
tree_pre = tmp_2;
tree_pro = tmp_1;
}
else {
int_pre = in_loc_1;
int_pro = in_loc_2;
tree_pre = tmp_1;
tree_pro = tmp_2;
}
if (int_pre > int_pro){
tree_pre.left = tree_pro;
}
else if (int_pre < int_pro){
int father_val = in[father_val(int_pro,i,in,pre)];
//find(father_val,tree_pro,first);
bianli(first,father_val,tree_pro);
}
}
return first;
}
private static int father_val(int int_pro,int now,int [] in,int [] pre){
for (int i = int_pro - 1;i>=0;i--){
for (int j = 0;j<now;j++){
if (in[i] == pre[j]){
return i;
}
}
}
return -1;
}
private static int loc(int val,int [] in){
for (int i=0; i< in.length;i++){
if (in[i] == val){
return i ;
}
}
return -1;
}
private static void bianli(TreeNode it,int val,TreeNode right){
if (it != null) {
if (it.val == val) {
it.right = right;
}
bianli(it.left, val,right);
bianli(it.right, val,right);
}
}
public static void main(String[] args){
int c1[] = {1,2,3,4,5,6,7};
int c2[] = {3,2,4,1,6,5,7};
TreeNode it = reConstructBinaryTree(c1,c2);
System.out.println(it.val);
}
}
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=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
return root;
}
private TreeNode reConstructBinaryTree(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=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
break;
}
return root;
}
}
思考
关于递归的return
正确
public int digui (){
while() return digui();
return ;
}
错误
错误的返回的是最外层的return 的值
public int digui(){
while () digui();
return ;
}
关于二叉树
三种遍历其实很简单:
- 先根再左后右 前序
- 先左再根后右 中序
- 先左再右后根 后序