import java.util.ArrayList; public class BinaryTree { private String data; private BinaryTree leftChild; private BinaryTree rightChild; // A constructor that takes root data only and // makes a tree with no children (i.e., a leaf) public BinaryTree(String d) { data = d; leftChild = null; rightChild = null; } // A constructor that takes root data as well as two subtrees // which then become children to this new larger tree. public BinaryTree(String d, BinaryTree left, BinaryTree right) { data = d; leftChild = left; rightChild = right; } // Get methods public String getData() { return data; } public BinaryTree getLeftChild() { return leftChild; } public BinaryTree getRightChild() { return rightChild; } // Set methods public void setData(String d) { data = d; } public void setLeftChild(BinaryTree left) { leftChild = left; } public void setRightChild(BinaryTree right) { rightChild = right; } // Return the height of the tree public int height() { if (this.leftChild == null) { if (this.rightChild == null) return 0; else return 1 + this.rightChild.height(); } else { if (this.rightChild == null) return 1 + this.leftChild.height(); else return 1 + Math.max(this.leftChild.height(), this.rightChild.height()); } } // Return all the leaves of the tree public ArrayList leafData() { ArrayList result = new ArrayList(); if (this.leftChild == null) { if (this.rightChild == null) result.add(this.data); else result.addAll(this.rightChild.leafData()); } else { result.addAll(this.leftChild.leafData()); if (this.rightChild != null) result.addAll(this.rightChild.leafData()); } return result; } }