【发布时间】:2020-02-22 05:54:44
【问题描述】:
我试图在不使用递归的情况下计算二叉树每个分支的总和。我正在尝试使用堆栈,但无法弄清楚如何修复我的代码以获得正确的总和。
public static List<Integer> branchSums(BinaryTree root) {
LinkedList<BinaryTree> toVisit = new LinkedList<>();
BinaryTree current = root;
List<Integer> sums = new ArrayList<>();
int sum = 0;
while (current != null || !toVisit.isEmpty()) {
while (current != null) {
sum += current.value;
toVisit.push(current);
current = current.left;
}
current = toVisit.pop();
// if found leaf add sum to results and decrement sum by current node
if (current.left == null && current.right == null) {
sums.add(sum);
sum -= current.value;
}
current = current.right;
}
return sums;
}
示例输入:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ /
8 9 10
示例输出 [15, 16, 18, 10, 11]
【问题讨论】:
-
你能举一个树的例子和预期的输出吗?问题不清楚,因为您的代码没有反映答案,所以问题不清楚
-
您应该做的第一件事是在循环的开头写一个注释,描述此时应该在堆栈上的内容,以及应该在
sum中的节点,以及什么是剩下要做的。然后确保每次迭代都是如此。
标签: java algorithm data-structures binary-tree