Question: Java - data structures P2 Suppose we want to create a method for the class BinaryTree that decides whether two trees have the same structure.
Java - data structures
P2
Suppose we want to create a method for the class BinaryTree that decides whether two trees have the same structure. Two trees t1 and t2 have the same structure if:
- If one has a left child, then both have left children and the left children are isomorphic, AND
- if one has a right child, then both have right children and the right children are isomorphic
The header of the method is:
public boolean isIsomorphic(BinaryTree
Write this method, using a private recursive method of the same name.
BinaryTree.java
//package TreePackage; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack ; // for Stack
public class BinaryTree
public BinaryTree(T rootData, BinaryTree
public void setTree(T rootData) { root = new BinaryNode
private void privateSetTree(T rootData, BinaryTree
if (leftTree != null) root.setLeftChild(leftTree.root); if (rightTree != null) root.setRightChild(rightTree.root); }
public T getRootData () { T rootData = null; if (root != null) rootData = root.getData(); return rootData; } public boolean isEmpty () { return root == null; } public void clear (){ root = null; } // getHeight and getNumberOfNodes call same functions in BinaryNode
public boolean hasNext () { return !nodeStack.isEmpty () || (currentNode != null); } // end hasNext
public T next () { BinaryNode< T > nextNode = null; // find leftmost node with no left child while (currentNode != null) { nodeStack.push (currentNode); currentNode = currentNode.getLeftChild (); } // end while // get leftmost node, then move to its right subtree if (!nodeStack.isEmpty ()) { nextNode = nodeStack.pop (); currentNode = nextNode.getRightChild (); } else throw new NoSuchElementException (); return nextNode.getData (); } // end next public void remove () { throw new UnsupportedOperationException (); } // end remove
} // end InorderIterator } // end BinaryTree
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
