Search code examples
javadata-structuresbinary-treetraversaltree-traversal

How to write a method taking argument BinaryTree<float> that uses preorder traversal to calculate X?


I can't for the life of me figure this out and was really someone could help me please, it's for revision purposes for an upcoming exam in Java:

• The following interface specifies the binary tree type.

interface BinaryTree 
{ 
   boolean isEmpty(); 
   T rootValue(); 
   BinaryTree leftChild(); 
   BinaryTree rightChild(); 
} 

Write a method that takes an argument of type BinaryTree [revise different argument types, character etc…(charcter and float are main ones, do rest if time)] and uses a [revise in-order and reorder] preorder traversal to calculate the sum of all of the numbers in the tree specified in the argument and return this sum as a value of type float.

Thanks in advance


Solution

  • Try this for preOrder traversal for calculating the sum for float

    float add(final BinaryTree node) {
    if (node == null) {
       return 0;
    }
    
    return (float)node.rootValue()+ add(node.leftChild()) + add(node.rightChild());
    }