java - 我需要对我的算法进行评论,以在二叉树中找到最长的连续序列
问题描述
// 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
}
算法是否正确并解决了问题?算法有效吗?我能做得更有效吗?
我是新来的,正在学习如何提问。如果有什么需要解决的问题,我很乐意提出建议。
解决方案
想想如果你在数组中解决同样的问题:
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);
}
推荐阅读
- javascript - 在 Angular 6 中找不到名称
- python - 如何从 Azure Databricks Spark 中的 DataFrame 获取特定的行和列
- javascript - 更改文本区域字体系列的功能(使用选项选择)
- javascript - CSS Floating ScrollTop按钮在iframe顶部不可点击
- shopware - 如何移动所有子类别 (ShopWare 5.4.6)
- http - 关于 shouldRedirectRLocked 方法的困惑(go1.11 src/net/http/server.go:2259)
- python - 重塑时出错
- java - 从Java中的多个文件夹中读取多个txt文件
- checkbox - RPA Express (Workfusion) Web 元素设置复选框
- angular6 - 是否可以创建一个自定义表单控件验证函数,该函数具有响应式表单的依赖项