N
N
ne_tot_net2020-06-24 23:58:03
Java
ne_tot_net, 2020-06-24 23:58:03

How to find maximum in Java binary tree?

my code:

public int max(Tree node) {
        int cur = (int) node.val();
        return maxInter(node, cur);
    }

    public int maxInter(Tree node, int maxValue) {
        if (node == null) {
            return maxValue;
        } else {
            int currentElement = (int) node.val;
            int tmpMaxValue = Math.max(currentElement, maxValue);
            maxInter(node.left, tmpMaxValue);
            maxInter(node.right, tmpMaxValue);
            System.out.println(tmpMaxValue); // просмотр макс значений
            return tmpMaxValue;
        }
    }

where is the mistake?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2020-06-25
@wataru

The fact that you assign an int to a parameter inside the function is not visible outside the function (the variable is passed by value, not by reference). Therefore, the result of recursive calls should be taken from the returned value, rather than hoping that the function itself will update tmpMaxValue.

D
Denis Zagaevsky, 2020-06-25
@zagayevskiy

That the results of recursive calls are not used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question