How can I go through every value in a tree?

Viewed 58

I have a function in a tree class :

class Tree {
Node root;
int countDivisibleBy(int divisor) {
    
}

}

How can i search through the tree and divide every value with the given divisor and in the end return the amount of numbers which can be divided by the divisor?

Node looks like this:

class Node {
int value;
Node left; 
Node right;

Node (int value) {
    this.value = value;
}

}

2 Answers

Recursive approach:

int countDivisibleByRecursive(Node root, int divisor) {
    int returnVal = 0;
    // check for divisibility here
    // ...
    returnVal += isDivisible ? 1 : 0;
    if(root.left != null){
        returnVal += countDivisibleByRecursive(root.left, divisor);
    }
    if(root.right != null){
        returnVal += countDivisibleByRecursive(root.right, divisor);
    }
    return returnVal;
}

The code can certainly be optimized. E. g. the variable doesn't need to exist, but it's easier to understand the code if it does.

Related