RDev
RDev

Reputation: 41

I need reviews on my algorithm that find longest consecutive sequence in binary tree

// Save the sequence with the maximum length
private static int max = 1;

/**
 * The method goal is to find the longest numerical sequence in binary tree
 * 
 * @param t - the tree for the searching
 * @param next - save the current sequence, the sequence to compare with the max
 */
public static void longestSeqPath(BinNode t, int next) {
    if (t == null)
        return;

    /*
     * First we check if we have any left then we check if the left node value is consecutive to the current node
     * if it is, we start with the counting
     */
    if (t.hasLeft() && t.getLeft().getValue() == t.getValue() + 1 || t.hasRight() && t.getRight().getValue() == t.getValue() + 1) {
        next++;
    } else if (next > max) {
        max = next;
        next = 1;
    }
    longestSeqPath(t.getLeft(), next);
    longestSeqPath(t.getRight(),next);

    // Note: Next is equals to 1 because we don't start to count the sequence from the first number in the sequence
}

Is the algorithm correct and solves the problem? Is the algorithm effective? Could I have done it more effectively?

I'm new here and learning how to ask questions. If there is anything to fix in the question I would love for suggestions.

Upvotes: 0

Views: 118

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 133975

Think of how you'd solve the same problem if you were doing it in an array:

for (i = 0; i < length; i++)
{
    // do all your logic here using a[i]
}

If you're doing an inorder traversal of a binary tree, that becomes:

void inorder(node)
{
    if (node == null) return;

    inorder(node.left);
    // do all your logic here, using node.value
    inorder(node.right);
}

Upvotes: 1

Related Questions