我是新的JAVA,如果不明白我的插入方法有什麼問題。 頭節點不會更新,也不會顯示任何內容。使用插入方法後BST的頭不更新
public class BinarySearchTree {
private Node head;
/**
* This is a default constructor for the root of the binary search tree
*/
public BinarySearchTree() {
head = null;
}
public Node Insert(Node head, Node node) {
if (head == null)
head = node;
else if (node.data < head.data)
head.left = Insert(head.left, node);
else if (node.data > head.data)
head.right = Insert(head.right, node);
return head;
如果我在構造函數head = new Node()上使用樹,但數據爲0的節點添加到我的樹中。
我該如何預防?
謝謝
編輯:
public class Node {
int data;
Node right;
Node left;
Node parent;
/**
* Constructor for the root in binary search tree
*/
public Node() {
}
public Node(int data) {
this.data = data;
this.right = null;
this.left = null;
//this.parent = null;
}
public Node(Node obj){
if(obj != null){
this.data = obj.data;
this.left = obj.left;
this.right = obj.right;
}
}
public void setData(int data, Node right, Node left, Node parent) {
this.data = data;
this.right = right;
this.left = left;
//this.parent = parent;
}
public int getData() {
return data;
}
public class BinarySearchTree {
private Node head;
/**
* This is a default constructor for the root of the binary search tree
*/
public BinarySearchTree() {
head = new Node();
}
public Node Insert(Node head, Node node) {
if (head == null)
head = node;
else if (node.data < head.data)
head.left = Insert(head.left, node);
else if (node.data > head.data)
head.right = Insert(head.right, node);
return head;
}
////////////////////////////////////////////////////////////////////////////////
public void printInOrder(Node node)
{
if (node != null)
{
printInOrder(node.left);
System.out.print(node.data + " - ");
printInOrder(node.right);
}
}
public void printPostOrder(Node node)
{
if (node != null)
{
printPostOrder(node.left);
printPostOrder(node.right);
System.out.print(node.data + " - ");
}
}
public void printPreOrder(Node node)
{
if (node != null)
{
System.out.print(node.data + " - ");
printPreOrder(node.left);
printPreOrder(node.right);
}
}
public Node getHead(){
return head;
}
////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args)
{
BinarySearchTree f = new BinarySearchTree();
/**
* Insert
*/
f.Insert(f.head, new Node(20));
f.Insert(f.head, new Node(5));
f.Insert(f.head, new Node(25));
f.Insert(f.head, new Node(3));
f.Insert(f.head, new Node(7));
f.Insert(f.head, new Node(27));
f.Insert(f.head, new Node(27));
/**
* Print
*/
f.printInOrder(f.head);
System.out.println("");
f.printPostOrder(f.head);
System.out.println("");
f.printPreOrder(f.head);
System.out.println("");
}
可以喲你請發佈整個代碼?與節點類一起?另外插入應根據約定 – JeD
寫在小寫字母感謝您的答覆。我編輯 – Silvering