我首先尝试将数据保存在 java 中自制堆栈数据结构的对象中。但问题是当我想返回该堆栈以在另一个函数中重用时,我可以在该函数中使用该堆栈,然后它在那里返回一个空堆栈。但是,就在上一行中,我已经打印了所有堆栈元素并且它不是空的。代码如下:
public Stack allLeafNodes(TreeNode root)
{
Stack stack= new Stack();
if (root == null)
return null;
if (root.getLeft() == null &&
root.getRight() == null)
{
stack.push(root.getData());
}
if (root.getLeft() != null)
allLeafNodes(root.getLeft());
if (root.getRight() != null)
allLeafNodes(root.getRight());
else{
stack.print(); // at this call all elements are getting printed
return stack; //but when it returns, the stack is empty
}
return stack;
}
答案 0 :(得分:0)
我认为在您的 print()
方法实现中您使用了 pop()
方法。对于它这种行为是正常的。来自 javadoc pop()
Removes the object at the top of this stack and returns that object as the value of this function.
无论如何,您的方法 print()
清除了您的堆栈。
答案 1 :(得分:0)
您似乎使用了一些自定义类 Stack
(不是 java.util.Stack
)和方法 print
的自定义实现,这可能使用 pop()
操作从而从堆栈中删除所有元素.
因此,方法print()
需要修改;可能值得重写 Stack
的方法 toString()
以确保堆栈内容不被修改并将其用于调试打印。
更新
另一个问题是递归方法 allLeafNodes
的实现,其中始终重新创建堆栈的结果实例,而它需要在对左右节点的递归调用中作为累加器传递:< /p>
public static Stack allLeafNodes(TreeNode root) {
return allLeafNodes(root, new Stack());
}
public static Stack allLeafNodes(TreeNode root, Stack stack) {
if (root == null)
return stack;
if (root.left == null && root.right == null) {
stack.push(root.data);
}
if (root.left != null)
allLeafNodes(root.left, stack);
if (root.right != null)
allLeafNodes(root.right, stack);
// stack.print(); // at this call all elements are getting printed
System.out.println(stack);
return stack;
}
否则,Stack
实现需要有一个类似于 Collections::addAll
的方法,该方法必须用于在从递归调用返回时添加“内部”叶节点的内容:
public static Stack allLeafNodes(TreeNode root) {
if (root == null)
return null;
Stack stack = new Stack();
if (root.left == null && root.right == null) {
stack.push(root.data);
}
if (root.left != null) {
Stack left = allLeafNodes(root.left);
if (null != left)
stack.addAll(left);
}
if (root.right != null) {
Stack right = allLeafNodes(root.right);
if (null != right)
stack.addAll(right);
}
// stack.print(); // at this call all elements are getting printed
System.out.println(stack);
return stack;
}