Write a method called combineWith that accepts another binary tree of integers as a parameter and combines the two trees into a new third tree that is returned. The new tree’s structure should be a union of the structures of the two original trees; it should have a node in any location where there was a node in either of the original trees (or both). The nodes of the new tree should store an integer indicating which of the original trees had a node at that position ( 1 if just the first tree had the node, 2 if just the second tree had the node, and 3 if both trees had the node). Your method should not change the structure or contents of either of the two original trees that are being combined.
For example, suppose IntTree variables t2 and t3 refer to reference trees #2 and #3 respectively. The call of t2.combineWith(t3) will return a reference to the following new tree. Keep in mind that nodes numbered 1 are those that appear only in t2 , nodes numbered 2 appear only in t3 , and nodes numbered 3 appear in both.
Add the above method to the IntTree class from this chapter. You may define additional private methods to implement your public method if necessary. Several problem descriptions refer to the following reference binary trees:
public IntTree combineWith(IntTree other)
{
IntTree newTree = new IntTree();
newTree.overallRoot =
combineWith(overallRoot, other.overallRoot);
return newTree;
}
private IntTreeNode combineWith(
IntTreeNode root, IntTreeNode otherRoot)
{
if(root == null && otherRoot == null)
{
return null;
}
else if(root == null && otherRoot != null)
{
return new IntTreeNode(
2, combineWith(null, otherRoot.left),
combineWith(null, otherRoot.right));
}
else if(root != null && otherRoot == null)
{
return new IntTreeNode(
1, combineWith(root.left, null),
combineWith(root.right, null));
}
else
{
return new IntTreeNode(
3, combineWith(root.left, otherRoot.left),
combineWith(root.right, otherRoot.right));
}
}