二叉搜索树前序遍历
我有一个关于二叉搜索树的先序遍历的问题。我知道该算法必须是什么样的,它非常简单:
void preOrder(Node node) {
print(node);
if (node.left() != null)
preOrder(node.left());
if (node.right() != null)
preOrder(node.right());
}
出于某种原因,我的函数仅打印出根节点的左侧子树,并打印出最低节点两次。我在右侧的一项上运行了 search
方法,它返回 true,所以我认为我的插入工作正常。为什么会发生这种情况?
我的代码如下。公共方法调用私有方法。在私有节点中,前两个 if 语句用于打印连接到该节点的左节点和右节点。最后两个执行实际的递归算法。
public void print() {
if (root == null)
System.out.println("Tree is empty");
else
print(root);
}
private void print(NodeBST node) {
printOut(node);
if (node.left() != null) {
System.out.print("Left: ");
printOut(node.left());
}
else
System.out.println("No left");
if (node.right() != null) {
System.out.print("Right: ");
printOut(node.right());
}
else
System.out.println("No right");
System.out.println("");
if (node.left() != null) {
node = node.left();
print(node);
}
if (node.right() != null) {
node = node.right();
print(node);
}
}
I have a question regarding preorder traversal of binary search tree. I know what the algorithm has to be like, its pretty simple:
void preOrder(Node node) {
print(node);
if (node.left() != null)
preOrder(node.left());
if (node.right() != null)
preOrder(node.right());
}
For some reason, my function prints out only the left side subtree of the root node, and it prints out the lowest node twice. I ran a search
method on one of the items on the right side and it returned true so I assume my insertion is working properly. Why is this happening?
My code is below. The public method calls the private one. In the private one, the first two if-statements are there to print the left and right nodes connected to that node. The last two do the actual recursive algorithm.
public void print() {
if (root == null)
System.out.println("Tree is empty");
else
print(root);
}
private void print(NodeBST node) {
printOut(node);
if (node.left() != null) {
System.out.print("Left: ");
printOut(node.left());
}
else
System.out.println("No left");
if (node.right() != null) {
System.out.print("Right: ");
printOut(node.right());
}
else
System.out.println("No right");
System.out.println("");
if (node.left() != null) {
node = node.left();
print(node);
}
if (node.right() != null) {
node = node.right();
print(node);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您遇到的一个错误是您覆盖了第一个
print(node)
之前的行上的node
,然后立即再次重用修改后的版本。想必您希望在执行if(node.right() != null)
测试时将node
设为原始值?您可以通过在第一个
if
中调用print(node.left());
来避免这种情况。Well one bug you have is that you overwrite
node
on the line just before the firstprint(node)
and then reuse the modified version again straight afterwards. Presumably you wantnode
to be the original value when doing theif(node.right() != null)
test?You can avoid this by e.g. just calling
print(node.left());
in the firstif
.