问题描述
因此,我目前正在尝试遵循FreeCodeCamp上的有关实现二叉树的教程,但是在添加和遍历我的树时遇到了麻烦。
由于某种原因,似乎可以将节点添加到树中,但是当我尝试通过迭代的预遍历遍历遍历树时,它只会拾取我的根节点。好像我的节点没有指向彼此。
我感觉问题出在我的add方法或遍历方法上,这两者都在下面。任何帮助将不胜感激。
添加方法:
public boolean add(T thing)
{
if(contains(thing))
{
return false;
} else {
root = add(root,thing);
count++;
return true;
}
}
private Node add(Node node,T thing)
{
if(node == null)
{
node = new Node(thing,null,null);
} else
{
if(thing.compareTo(node.value) <0)
{
if(node.left == null)
{
node.left = node = new Node(thing,null);
} else{
node.left =add(node.left,thing);
}
}
else
{
if(node.right == null)
{
node.right = node = new Node(thing,null);
}else {
node.right = add(node.right,thing);
}
}
}
return node;
}
遍历:
public void traverse()
{
preorder(root);
}
private void preorder(Node node)
{ int iteration=0;
java.util.Stack<Node> stack = new java.util.Stack<Node>();
System.out.println( "root is: " +node.value);
stack.push(node);
while(stack.empty() == false)
{
Node current = stack.pop();
System.out.println("in preorder: "+current.value);
if(current.right != null)
{
stack.push(current.right);
}
if(current.left != null)
{
stack.push(current.left);
}
iteration++;
}
System.out.println("iteration: "+iteration);
}
解决方法
在添加树时,您没有遍历树。检查我的树插入方法以了解主意:-
void insert(Node temp,int value) {
if(temp==null){
temp=new Node(value,null,null);
this.root=temp;
}
else{
Queue<Node> q = new LinkedList<>();
q.add(temp);
while (!q.isEmpty()) {
temp = q.peek();
q.remove();
if (temp.left == null) {
temp.left = new Node(value,null);
break;
} else
q.add(temp.left);
if (temp.right == null) {
temp.right =new Node(value,null);
break;
} else
q.add(temp.right);
}
}
}