Redian新闻
>
丝丝说,她在发包子前问一下
avatar
丝丝说,她在发包子前问一下# Joke - 肚皮舞运动
S*C
1
4.9 You are given a binary tree in which each node contains a value. Design
an algorithm to print all paths which sum to a given value. The path does
not need to start or end at the root or a leaf
Page 237
他的答案如下
package Question4_9;
import CtCILibrary.TreeNode;
public class Question {

public static void findSum(TreeNode node, int sum, int[] path, int level
) {
if (node == null) {
return;
}

/* Insert current node into path */
path[level] = node.data;

int t = 0;
for (int i = level; i >= 0; i--){
t += path[i];
if (t == sum) {
print(path, i, level);
}
}

findSum(node.left, sum, path, level + 1);
findSum(node.right, sum, path, level + 1);

/* Remove current node from path. Not strictly necessary, since we
would
* ignore this value, but it's good practice.
*/
path[level] = Integer.MIN_VALUE;
}

public static int depth(TreeNode node) {
if (node == null) {
return 0;
} else {
return 1 + Math.max(depth(node.left), depth(node.right));
}
}

public static void findSum(TreeNode node, int sum) {
int depth = depth(node);
int[] path = new int[depth];
findSum(node, sum, path, 0);
}
private static void print(int[] path, int start, int end) {
for (int i = start; i <= end; i++) {
System.out.print(path[i] + " ");
}
System.out.println();
}
public static void main(String [] args){
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(1);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(8);
root.right.left = new TreeNode(2);
root.right.right = new TreeNode(6);
findSum(root, 8);
}
}
这种解法错在只能求单边的单线段path,不能求倒勾形状的path,而倒钩型path显然是
不能忽略的。
比如下面的例子中如果sum等于9显然是存在path的: 3-5-1
但这种解法根本把他忽略了。Career cup出到第5版了还犯这种幼稚的错误真是让人无
语。
5

3 1

4 8 2 6
这题谁有正确的解法?
avatar
I*a
2
投票做个选则题,哪个更美女. 这可不是我编的,不信你们问她.
dream 的版五
还是
肚皮的版四
avatar
s*y
3
她的解法对她的题没有错, 你理解成了leetcode 那道题了http://oj.leetcode.com/problems/binary-tree-maximum-path-sum/. 我觉得作者对path的理解是自上向下,不能自下向上。我做leetcode 的时候也是cc150 作者那么理解的。 比如1->2->3 这是个linkedlist path 是1, 2, 3 , 按你的理解是3,2,1 也算path,明显3不能走到2 ,这就是cc150的理解,我觉得。
avatar
R*d
4
投两个能拿两包子么?
avatar
S*C
5
那应该明说 print all downward paths ...
否则这答案肯定不对

【在 s******y 的大作中提到】
: 她的解法对她的题没有错, 你理解成了leetcode 那道题了http://oj.leetcode.com/problems/binary-tree-maximum-path-sum/. 我觉得作者对path的理解是自上向下,不能自下向上。我做leetcode 的时候也是cc150 作者那么理解的。 比如1->2->3 这是个linkedlist path 是1, 2, 3 , 按你的理解是3,2,1 也算path,明显3不能走到2 ,这就是cc150的理解,我觉得。
avatar
M*e
6
太无耻了

【在 I*****a 的大作中提到】
: 投票做个选则题,哪个更美女. 这可不是我编的,不信你们问她.
: dream 的版五
: 还是
: 肚皮的版四

avatar
R*d
7
奔图或者发包子, 不要让大家失望哦

【在 M*****e 的大作中提到】
: 太无耻了
avatar
M*e
8
发包子
反正都是小白兔的钱

【在 R******d 的大作中提到】
: 奔图或者发包子, 不要让大家失望哦
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。