【发布时间】:2012-01-16 06:20:50
【问题描述】:
我有这个用于二叉树创建和遍历的代码
class Node
{
Integer data;
Node left;
Node right;
Node()
{
data = null;
left = null;
right = null;
}
}
class BinaryTree
{
Node head;
Scanner input = new Scanner(System.in);
BinaryTree()
{
head = null;
}
public void createNode(Node temp, Integer value)
{
Node newnode= new Node();
value = getData();
newnode.data = value;
temp = newnode;
if(head==null)
{
head = temp;
}
System.out.println("If left child exits for ("+value+") enter y else n");
if(input.next().charAt(0)=='y')
{
createNode(temp.left, value);
}
System.out.println("If right child exits for ("+value+") enter y else n");
if(input.next().charAt(0)=='y')
{
createNode(temp.right, value);
}
}
public Integer getData()
{
out.println("Enter the value to insert:");
return (Integer)input.nextInt();
}
public void print()
{
inorder(head);
}
public void inorder(Node node)
{
if(node!=null)
{
inorder(node.left);
System.out.println(node.data);
inorder(node.right);
}
else
return;
}
}
class BinaryTreeWorker
{
static BinaryTree treeObj = null;
static Scanner input = new Scanner(System.in);
public static void displaymenu()
{
int choice;
do{
out.print("\n Basic operations on a tree:");
out.print("\n 1. Create tree \n 2. Insert \n 3. Search value \n 4. print list\n Else. Exit \n Choice:");
choice = input.nextInt();
switch(choice)
{
case 1:
treeObj = createBTree();
break;
case 2:
treeObj.createNode(null, null);
break;
case 3:
//searchnode();
break;
case 4:
treeObj.print();
break;
default:
return;
}
}while(true);
}
public static BinaryTree createBTree()
{
return new BinaryTree();
}
public static void main(String[] args)
{
displaymenu();
}
}
它编译并运行。但是我认为中序遍历有问题。
我创建了下面的树,
2 1 3但它只打印 2 个。
【问题讨论】:
-
为什么你认为它有问题?它会产生不正确的输出吗?期待什么?你实际上得到了什么?
-
仅供参考,将用户界面(尤其是阻塞模式调用)与域对象逻辑混合是一个非常糟糕的习惯。我会考虑将逻辑分离出来;这将使调试变得更加容易。首先查看模型视图控制器 (MVC) 范例。
-
另一种编码风格评论:
inorder不需要Node的实例来运行,让它静态! [或者更好:让它不接受任何参数,并使用this而不是传递Node作为参数] -
这不是家庭作业,但我是为了自学。我已将输出添加到原始帖子中
-
我还是想不通createNode方法有什么问题!!
标签: java algorithm binary-tree