重建二叉树
程序员文章站
2022-04-02 21:27:31
...
题目描述:
根据二叉树的前序和中序,或者后序和中序,重建一颗二叉树
代码:
package offer;
class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public class chongJianErChaShu{
public static void main(String args[]) {
int a[] = {1,2,4,7,3,5,6,8};
int b[] = {4,7,2,1,5,3,8,6};
int c[] = {7,4,2,5,8,6,3,1};
TreeNode root = slove(a,0,a.length-1,b,0,b.length-1);
TreeNode root2 = slove2(c,0,c.length-1, b,0,b.length-1);
print(root);
System.out.println();
print(root2);
}
public static TreeNode slove(int a[],int astart, int aend, int b[], int bstart, int bend) {
if (aend < astart || bend < bstart) {
return null;
}
TreeNode root = new TreeNode(a[astart]);
for (int i = 0; i<= bend; i++) {
if (a[astart] == b[i]) {
/* 参数传递这里有点绕人,绕了我好长时间,
* 可能自己真的脑筋转不过玩,最后把(bend-i)当做一个差值变量还好理解点。 */
root.left = slove(a, astart+1, aend-(bend-i),b, bstart, i-1);
root.right = slove(a,aend-(bend-i)+1 ,aend ,b, i+1,bend );
}
}
return root;
}
public static TreeNode slove2(int a[], int astart, int aend, int b[], int bstart, int bend) {
if (astart> aend || bstart > bend) {
return null;
}
TreeNode root = new TreeNode(a[aend]);
for (int i = 0; i<= bend; i++) {
if (a[aend] == b[i]) {
root.left = slove2(a, astart,aend-(bend-i)-1 ,b, bstart,i-1 );
root.right = slove2(a,aend-(bend-i),aend-1,b, i+1,bend);
}
}
return root;
}
public static void print(TreeNode pHead) {
if (pHead == null) {
return ;
}
System.out.print(pHead.val+" ");
print(pHead.left);
print(pHead.right);
}
}