Java 二叉树。打印 InOrder 遍历
我在打印二叉树的有序遍历时遇到一些问题。即使在树中插入许多项目后,它也只打印 3 个项目。
public class BinaryTree {
private TreeNode root;
private int size;
public BinaryTree(){
this.size = 0;
}
public boolean insert(TreeNode node){
if( root == null)
root = node;
else{
TreeNode parent = null;
TreeNode current = root;
while( current != null){
if( node.getData().getValue().compareTo(current.getData().getValue()) <0){
parent = current;
current = current.getLeft();
}
else if( node.getData().getValue().compareTo(current.getData().getValue()) >0){
parent = current;
current = current.getRight();
}
else
return false;
if(node.getData().getValue().compareTo(parent.getData().getValue()) < 0)
parent.setLeft(node);
else
parent.setRight(node);
}
}
size++;
return true;
}
/**
*
*/
public void inOrder(){
inOrder(root);
}
private void inOrder(TreeNode root){
if( root.getLeft() !=null)
this.inOrder(root.getLeft());
System.out.println(root.getData().getValue());
if( root.getRight() != null)
this.inOrder(root.getRight());
}
}
I am having some problems printing an inOrder traversal of my binary tree. Even after inserting many items into the tree it's only printing 3 items.
public class BinaryTree {
private TreeNode root;
private int size;
public BinaryTree(){
this.size = 0;
}
public boolean insert(TreeNode node){
if( root == null)
root = node;
else{
TreeNode parent = null;
TreeNode current = root;
while( current != null){
if( node.getData().getValue().compareTo(current.getData().getValue()) <0){
parent = current;
current = current.getLeft();
}
else if( node.getData().getValue().compareTo(current.getData().getValue()) >0){
parent = current;
current = current.getRight();
}
else
return false;
if(node.getData().getValue().compareTo(parent.getData().getValue()) < 0)
parent.setLeft(node);
else
parent.setRight(node);
}
}
size++;
return true;
}
/**
*
*/
public void inOrder(){
inOrder(root);
}
private void inOrder(TreeNode root){
if( root.getLeft() !=null)
this.inOrder(root.getLeft());
System.out.println(root.getData().getValue());
if( root.getRight() != null)
this.inOrder(root.getRight());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看来您在插入时没有正确遍历树,以找到新节点的正确位置。现在,您总是在根的一个子节点处插入,因为插入代码位于
while
循环内 - 它应该在之后:It seems that you are not traversing the tree properly upon insertion, to find the right place for the new node. Right now you are always inserting at one child of the root, because the insertion code is inside the
while
loop - it should be after it:你的插入方法有问题。它找到正确的父节点来附加新元素,但在途中它弄乱了整个树。您应该将插入代码移出 while 循环:
You insert method has a problem. It finds the right parent node to attach the new element to, but on the way it messes up the whole tree. You should move the insertion code out of the while loop:
嘿,伙计们,这是一个简单的..试试这个..它对我很有用......
hey fellows here is one simple one.. try this out.. it works for me well...