Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class BinaryNode <T>{
- private T data;
- private BinaryNode<T> leftChild;
- private BinaryNode<T> rightChild;
- public BinaryNode(){
- this(null);//call next constructor
- }
- public BinaryNode(T dataPortion){
- this(dataPortion, null, null); // call next constructor
- }
- public BinaryNode(T dataPortion, BinaryNode<T> newLeftChild, BinaryNode<T> newRightChild){
- data = dataPortion;
- leftChild = newLeftChild;
- rightChild = newRightChild;
- } // end of constructor
- public T getData(){
- return data;
- }
- public void setData( T newData){
- data = newData;
- }
- public BinaryNode<T> getLeftChild(){
- return leftChild;
- }
- public void setLeftChild(BinaryNode<T> newLeftChild){
- leftChild = newLeftChild;
- }
- // checks if the node is a leaf or not
- public boolean isLeaf(){
- return (leftChild == null) && (rightChild == null);
- }
- public BinaryNode<T> getRightChild(){
- return rightChild;
- }
- public void setRightChild(BinaryNode<T> newRightChild){
- rightChild = newRightChild;
- }
- // calculates the number of nodes in the tree
- public int getNumberOfNodes(){
- int leftNum = 0 ;
- int rightNum = 0;
- if(leftChild != null)
- leftNum = leftChild.getNumberOfNodes();
- if(rightChild !=null)
- rightNum = rightChild.getNumberOfNodes();
- return 1+leftNum +rightNum;
- }
- // empty method for getHeight
- public int getHeight(){
- return getHeight(this); // calls the private recursive method
- }
- // the recursive method to count the height of the tree
- private int getHeight(BinaryNode<T> node){
- int height = 0;
- if(node != null)
- height = 1 + Math.max(getHeight(node.getLeftChild()),getHeight(node.getRightChild()));
- return height;
- }
- public BinaryNode<T> copy(){
- BinaryNode<T> newRoot = new BinaryNode<> (data);
- if(leftChild != null)
- newRoot.setLeftChild(leftChild.copy());
- if(rightChild != null)
- newRoot.setRightChild(rightChild.copy());
- return newRoot;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement