Java 最大轨迹二叉树
--爪哇-- 为了那棵树 我需要找到“最大轨道” 所以对于这棵树,它是39(5+4+30) 我需要一个这样做的函数(复杂性O(n)) 有人能帮我吗Java 最大轨迹二叉树,java,Java,--爪哇-- 为了那棵树 我需要找到“最大轨道” 所以对于这棵树,它是39(5+4+30) 我需要一个这样做的函数(复杂性O(n)) 有人能帮我吗 public static int GetTreePath(BinTreeNode<Integer> t){ if (t==null) return 0; if (t.IsLeve()){ return t.getInfo(); }else{
public static int GetTreePath(BinTreeNode<Integer> t){
if (t==null)
return 0;
if (t.IsLeve()){
return t.getInfo();
}else{
GetTreePath(t.getLeft());
GetTreePath(t.getRight());
}
return t.getInfo();
}
public static int GetTreePath(BinTreeNode t){
如果(t==null)
返回0;
if(t.IsLeve()){
返回t.getInfo();
}否则{
GetTreePath(t.getLeft());
GetTreePath(t.getRight());
}
返回t.getInfo();
}
只是稍微修改了一下代码,以便最大限度地利用两个可能的子树
public static int GetTreePath(BinTreeNode<Integer> t){
if (t==null)
return 0;
if (t.IsLeve()){
return t.getInfo();
}else{
return Math.max(
GetTreePath(t.getLeft()),
GetTreePath(t.getRight())
) + t.getInfo();
}
}
public static int GetTreePath(BinTreeNode t){
如果(t==null)
返回0;
if(t.IsLeve()){
返回t.getInfo();
}否则{
返回Math.max(
GetTreePath(t.getLeft()),
GetTreePath(t.getRight())
)+t.getInfo();
}
}
有一个DP解决方案
F(i) = max(F(child) + value(i))
计算(f)
从叶到根,或递归并保存f(i)
如果这是作业,请将其标记为这样的。提示:研究递归算法。你可能想发布一些代码,向社区展示你到目前为止所拥有的,而不是含糊不清地寻求帮助。好的,这是我的代码。我没有发布它,因为我认为它甚至不接近答案。请坚持Jaa命名约定。@JBNizet:通常我们称之为“Java”。-)
F(i) = max(F(child) + value(i))