如何填充BST并以有序方式进行打印

时间:2019-05-09 09:35:48

标签: java static tree binary-search-tree

我正在尝试使用此代码填充BST,然后以InOrder遍历格式打印它。但是根结点没有被填充而没有任何错误,并且输出为:“ root is empty”,因此如何更正此代码,以便将我的BST填充到结点根中。

我试图将Node的根设置为静态,我认为可能是无法通过每种方法访问根节点,但它无法正常工作,试图更改Node的名称,但它也无法正常工作。 / p>

import java.util.*;
import java.io.*;
import java.lang.*;

class Node{
    int data; Node left; Node right;
    public Node(int data) {
        this.data = data;
        left = null;
        right = null;

    }
}
public class insert_tree {
    static Node root;   

     insert_tree() //constructor
     { 
        root = null; 
     } 
    public void addNode(int value) { // public method is called by the object and this public method calls the private method in which the root is also passed.
        root = add(root, value);
    }
    private Node add(Node node, int value) {
        if(node == null) {
            return node;
        }
        if(value < node.data) {
            node.left = add(node.left, value);
        }       
        else if(value > node.data) {
            node.right = add(node.right, value);
        }
        else {
            return node;
        }
        return node;
    }

    private void inOrder(Node node) {
//      node = root;
        if(node != null) {
            inOrder(node.left);
            System.out.print(node.data + " ");
            inOrder(node.right);
        }
        else {
            System.out.print("root is empty");
        }
        //return null;
    }
    public void inorder() {
        inOrder(root);
    }
   private void printRoot(Node root) {
      System.out.println(root.data);
   }
   public void print() {
      printRoot(root);
   }
    public static void main(String args[]) {
        insert_tree obj = new insert_tree();
        obj.addNode(20);
        obj.addNode(14);
        obj.addNode(25);
        obj.addNode(10);
        obj.addNode(16);
        obj.addNode(25);
        obj.addNode(21);
        obj.addNode(30);
        //printing the tree
        obj.inorder();



    }
}


输出应该是树的有序遍历。

1 个答案:

答案 0 :(得分:0)

public void addNode(int value) { // public method is called by the object and this public method calls the private method in which the root is also passed.
    root = add(root, value);
}
private Node add(Node node, int value) {
    if(node == null) {
        node = new Node(value);
    }
    else if(value == node.data) {
        node.data = value;
    }
    else if(value < node.data) {
        node.left = add(node.left, value);
    }
    else {
        node.right = add(node.right, value);
    }
    return node;
}