Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1.  
  2. class BinaryNode <T>{
  3. private T data;
  4. private BinaryNode<T> leftChild;
  5. private BinaryNode<T> rightChild;
  6.  
  7. public BinaryNode(){
  8. this(null);//call next constructor
  9. }
  10. public BinaryNode(T dataPortion){
  11. this(dataPortion, null, null); // call next constructor
  12. }
  13. public BinaryNode(T dataPortion, BinaryNode<T> newLeftChild, BinaryNode<T> newRightChild){
  14. data = dataPortion;
  15. leftChild = newLeftChild;
  16. rightChild = newRightChild;
  17. } // end of constructor
  18. public T getData(){
  19. return data;
  20. }
  21. public void setData( T newData){
  22. data = newData;
  23. }
  24. public BinaryNode<T> getLeftChild(){
  25. return leftChild;
  26. }
  27. public void setLeftChild(BinaryNode<T> newLeftChild){
  28. leftChild = newLeftChild;
  29. }
  30. // checks if the node is a leaf or not
  31. public boolean isLeaf(){
  32. return (leftChild == null) && (rightChild == null);
  33. }
  34. public BinaryNode<T> getRightChild(){
  35. return rightChild;
  36. }
  37. public void setRightChild(BinaryNode<T> newRightChild){
  38. rightChild = newRightChild;
  39. }
  40. // calculates the number of nodes in the tree
  41. public int getNumberOfNodes(){
  42. int leftNum = 0 ;
  43. int rightNum = 0;
  44. if(leftChild != null)
  45. leftNum = leftChild.getNumberOfNodes();
  46. if(rightChild !=null)
  47. rightNum = rightChild.getNumberOfNodes();
  48. return 1+leftNum +rightNum;
  49. }
  50. // empty method for getHeight
  51. public int getHeight(){
  52. return getHeight(this); // calls the private recursive method
  53. }
  54. // the recursive method to count the height of the tree
  55. private int getHeight(BinaryNode<T> node){
  56. int height = 0;
  57. if(node != null)
  58. height = 1 + Math.max(getHeight(node.getLeftChild()),getHeight(node.getRightChild()));
  59. return height;
  60. }
  61. public BinaryNode<T> copy(){
  62. BinaryNode<T> newRoot = new BinaryNode<> (data);
  63. if(leftChild != null)
  64. newRoot.setLeftChild(leftChild.copy());
  65. if(rightChild != null)
  66. newRoot.setRightChild(rightChild.copy());
  67. return newRoot;
  68. }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement