【发布时间】:2011-03-08 15:54:54
【问题描述】:
计算两个节点之间的最长路径。
路径在拱形中。
方法的签名是:
public static int longestPath(Node n)
在下面的示例二叉树中,它是 4(通过 2-3-13-5-2)。
这就是我现在拥有的,对于给定的树,它只返回 0。
public static int longestPath(Node n) {
if (n != null) {
longestPath(n, 0);
}
return 0;
}
private static int longestPath(Node n, int prevNodePath) {
if (n != null && n.getLeftSon() != null && n.getRightSon() != null) {
int currNodePath = countLeftNodes(n.getLeftSon()) + countRightNodes(n.getRightSon());
int leftLongestPath = countLeftNodes(n.getLeftSon().getLeftSon()) + countRightNodes(n.getLeftSon().getRightSon());
int rightLongestPath = countLeftNodes(n.getRightSon().getLeftSon()) + countRightNodes(n.getRightSon().getRightSon());
int longestPath = currNodePath > leftLongestPath ? currNodePath : leftLongestPath;
longestPath = longestPath > rightLongestPath ? longestPath : rightLongestPath;
longestPath(n.getLeftSon(), longestPath);
longestPath(n.getRightSon(), longestPath);
return longestPath > prevNodePath ? longestPath : prevNodePath;
}
return 0;
}
private static int countLeftNodes(Node n) {
if (n != null) {
return 1+ countLeftNodes(n.getLeftSon());
}
return 0;
}
private static int countRightNodes(Node n) {
if (n != null) {
return 1+ countRightNodes(n.getRightSon());
}
return 0;
}
我知道我在某处遗漏了一个关键概念……当我尝试跟踪执行流程时,我的大脑发疯了……
我是否正确地说,通过在根、其左右节点之间找到最长路径,然后在其左右节点上递归,将它们从先前方法调用中传递给它们的最长路径,最后(何时?)返回最长路径,我不知道你是怎么退货的……
【问题讨论】:
-
如何处理二叉树本质上是链表的情况?例如,2-3-13(13 是根,3 是 13 的左边,2 是 3 的左边)。结果应该是 2 吗?
标签: java algorithm recursion binary-tree