Мне нужны обзоры по моему алгоритму, которые находят самую длинную последовательность в двоичном дереве - PullRequest
1 голос
/ 01 мая 2020
// 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
}

Правильн ли алгоритм и решает проблему? Эффективен ли алгоритм? Мог бы я сделать это более эффективно?

Я новичок здесь и учусь задавать вопросы. Если есть что-то, что можно исправить в этом вопросе, я хотел бы получить предложения.

1 Ответ

1 голос
/ 01 мая 2020

Подумайте, как бы вы решили ту же проблему, если бы делали это в массиве:

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

Если вы выполняете обход по порядку двоичного дерева, оно становится:

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

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