我需要对我的算法进行评估,以找到二叉树中最长的连续序列

问题描述 投票:1回答:1
// 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
}

算法是否正确并解决了问题?该算法有效吗?我能做得更有效吗?

我是新来的,正在学习如何提问。如果您要解决的问题有什么要解决的,我希望提出建议。

java algorithm data-structures binary-tree review
1个回答
0
投票

想想如何在数组中解决相同的问题:

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.