a**d 发帖数: 85 | 1 You are given a binary tree in which each node contains a value. Design an
algorithm to print all paths which sum up to that value. Note that it can be
any path in the tree - it does not have to start at the root.
int tmp = sum; buffer.add(head.data);
for (int i = level;i >- 1; i--){
tmp -= buffer.get(i);
if (tmp == 0) print(buffer, i, level);
}
findsum(head.left,sum,c1,level+1)
findsum(head.right,sum,c2,level+1)
里面讲的思路是从每个node往上看是否和为sum.
我觉得这样写只是考虑path不从root开始,而且只是从上往下的path,如果理解成path
可以从任意一个node开始呢?就是说比如:1
/
2 3
path:2-1-3也考虑。
这样应该怎么写呢?
谢谢 |