# attach binary trees to another binary tree

the method attaches the internal structure of trees T1 and T2 as the respective left and right subtrees of leaf reference p and resets T1 and T2 to empty trees; an error condition occurs if p is not a leaf.

```
public void attach(Node p, BinaryTree t1, BinaryTree t2) {
if (p.left == null) { //logic error??
p.left = t1.root;
t1.root = null;
}
if (p.right == null) {
p.right = t2.root;
t1.root = null;
}
else
System.out.print("is not leaf");
}
```

### 1 Answer

Dont delete the t1 and t2 roots, when you assign t1.root to p.left and t2.root to p.right the task its done.

This is because java use t1 and t2 objects to reference p.left and p.right

```
public void attach(Node p, BinaryTree t1, BinaryTree t2){
if(p.left ==null){
p.left=t1.root;
}
if(p.right==null){
p.right=t2.root;
}
else
System.out.print("is not leaf");
}
```

J.del Rey
posted this

## Have an answer?

JD