简体   繁体   中英

Printing Java Binary search tree

How to print out a binary search tree in java? I have written the code to insert to the tree but without being able to print the tree i am insure if the elements are adding. I will post my code below.

public class TreeNode {

    TreeNode left;
    TreeNode right;
    TreeNode root;

    int data;

    public TreeNode(int d) {

        data = d;
        left = right = null;
        root = null;

    }

    public synchronized void insert(int d) {
        if (root == null){
            root = new TreeNode( d );
        }
        if (d < data) {
            if (left == null) {
                left = new TreeNode(d);
            } else {
                left.insert(d);
            }
        } else if (d > data) {
            if (right == null) {
                right = new TreeNode(d);
            } else {
                right.insert(d);
            }
        }
    }

    public TreeNode treeSearch(TreeNode root, int target) {
        if (root != null) {
            if (target < root.data) {
                root = treeSearch(root.left, target);
            } else if (target > root.data) {
                root = treeSearch(root.right, target);
            }
        }
        return root;
    }
}

You may use following method:

 void printTree(TreeNode node, String prefix)
 {
    if(node == null) return;

    System.out.println(prefix + " + " + node.data);
    printTree(node.left , prefix + " ");
    printTree(node.right , prefix + " ");
 }

Initial call should be printTree( root,""); from where you want to print the tree. Here root is reference of root node.

UPDATED:
You can see this code working here

you can print the tree data like this.

public void printTree(TreeNode root) {
        if (root == null) return;
        System.out.println(root.data);
        printTree(root.left);
        printTree(root.right);
    }   
private void print(PrintWriter out) {
    print(root, out, "");
}

private void print(TreeNode subtree, PrintWriter out, String indent) {
    if (subtree != null) {
        print(subtree.left, out, indent + "--");
        out.printf("%s %s%n", indent, subtree.data);
        print(subtree.right, out, indent + "--");
    }
}

Infix order: Left - root - right

public String printInfix(TreeNode root) {//prints all the words in the tree in infix order
    if(root==null) {
        return "";
    }

     return printAll(root.left+" "+root.data+" "+printAll(root.right);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM