【发布时间】:2020-11-03 03:42:10
【问题描述】:
我希望你今天过得很好。对于这个二叉搜索树的实现,我需要第二个意见,它的插入和打印方法。我知道我可以以一种可能有点令人费解的方式实现这一点,但我想知道我在哪里搞砸了。当我运行程序时,它会输出以下内容:
Root value is: 3
Val inserted to left of root: 1
Val inserted at right node: 1
Root value is: 3
Val inserted at left node: 0
Root value is: 3
Val inserted to right of root: 4
Val inserted at right node: 4
Root value is: 3
Val inserted at right node: 5
0
1
1
3
4
4
5
我希望这个程序输出树 inOrder,输入为:3,1,0,4,5。
这是我现在的代码,谢谢你的第二眼。
class tree {
Node root = null;
//Constructor
tree(int value){
root = new Node(value);
}
//insert
void insertStart(int val){
System.out.println("Root value is: "+root.value);
//Check val against root & root has none children
if(val < root.value && root.left == null){
root.left = new Node(val);
System.out.println("Val inserted to left of root: "+root.left.value);
}
if(val > root.value && root.right == null){
root.right = new Node(val);
System.out.println("Val inserted to right of root: "+root.right.value);
}
//Check val against root & root has two children
if(val < root.value){
//insertRecursion left
insert(root.left, val);
}else{
//insertRecursion right
insert(root.right, val);
}
}
void insert(Node node, int val){
//compare the node's value to val
if(val < node.value){
//check if left has children if yes call insert again else make new node with val
if(node.left != null){
insert(node.left, val);
}else{
node.left = new Node(val);
System.out.println("Val inserted at left node: "+val);
}
}else{
//check if right has children if yes call insert again else make new node with val
if(node.right != null){
insert(node.right, val);
}else{
node.right = new Node(val);
System.out.println("Val inserted at right node: "+val);
}
}
}
//lookup -> return value else return null/zero/print no number here
int lookUp(int val){
System.out.println("Number not found");
return 0;
}
//remove
void remove(int val){
}
void printStart(){
printInOrder(root);
}
void printInOrder(Node node){
if(node == null){
return;
}
printInOrder(node.left);
System.out.println(""+node.value);
printInOrder(node.right);
}
class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
right = null;
left = null;
}
}
}
public class binaryTree{
public static void main(String[] args) {
tree tree = new tree(3);
tree.insertStart(1);
tree.insertStart(0);
tree.insertStart(4);
tree.insertStart(5);
tree.printStart();
}
}
【问题讨论】:
-
我认为像您这样的打印是对树的“按顺序”搜索。您拥有的仅数字列表看起来像是对树的“预排序”搜索,这就是您按排序顺序打印树的方式。您应该确保您了解这两个概念并正确使用它们来解决这个问题。
标签: java algorithm data-structures binary-tree binary-search-tree