【发布时间】:2014-07-14 16:40:46
【问题描述】:
为什么它为父母和孩子输出null!?逻辑对我来说似乎很好...... 它不应该为 left、right 和 parent 打印 null,因为它们是用 left = left.toString(); 更新的。等等
主要方法:
public class TreeInfo
{
public static void main(String[] args)
{
BinaryTree<Integer> left = new BinaryTree<Integer>(5);
System.out.println(left);
BinaryTree<Integer> right = new BinaryTree<Integer>(9);
BinaryTree<Integer> parent = new BinaryTree<Integer>(1);
BinaryTree<Integer> a = new BinaryTree<Integer>(parent, 5, left, right);
System.out.println(a);
}
}
.
方法类:
import java.math.*;
import java.lang.*;
import java.util.*;
public class BinaryTree<E> implements BinaryTreeNode<E>
{
protected E data;
protected BinaryTreeNode<E> parent;
protected BinaryTreeNode<E> left;
protected BinaryTreeNode<E> right;
public BinaryTree(BinaryTree<E> parent, E data, BinaryTree<E> left, BinaryTree<E> right)
{
this.data = data;
this.left = left;
this.right = right;
}
public BinaryTree(E data)
{
this(null, data, null, null);
}
public E getData()
{
return this.data;
}
public BinaryTreeNode<E> getParent()
{
return this.parent;
}
public boolean isEmpty()
{
return data == null;
}
public boolean isLeaf()
{
return left == null && right == null;
}
public boolean hasLeft()
{
return left != null;
}
public boolean hasRight()
{
return right != null;
}
public int getNONodes()
{
int count = 1;
if (hasLeft())
{
count += left.getNONodes();
}
if (hasRight())
{
count += right.getNONodes();
}
return count;
}
public String toString() {
if (isLeaf()) {
return data.toString();
}
else {
String root = "null", parent = "null", left = "null", right = "null";
root = data.toString();
if (left != null) {
left = left.toString();
}
if (right != null) {
right = right.toString();
}
if (parent != null)
{
parent = parent.toString();
}
return root + " (" + parent + ", " + left + ", " + right + ")";
}
}
}
接口:
public interface BinaryTreeNode<E>
{
E getData(); // Returns a reference to data and a reference to its left and right subtrees.
BinaryTreeNode<E> getParent(); // Returns the parent of this node, or null if this node is a root.
boolean isEmpty(); // returns false if the tree is non-empty and true if it is.
boolean hasLeft();
boolean hasRight();
boolean isLeaf();
int getNONodes(); // returns total number of nodes in the Binary Tree.
String toString();
}
运行时输出:
5
5 (null, null, null)
Process completed.
【问题讨论】:
-
在调试器中启动它,或者放入一些额外的打印输出,您应该很快就能找到问题所在。命中:this.data 设置在哪里?
标签: java binary-tree main