简体   繁体   中英

Java Binary Tree Main Method

I've got a class Node

class Node{
    int val; 
    Node parent; 
    Node left; 
    Node right; 

    public Node (int val){
        this.val = val;
    }
}

And I have a few methods:

 public class Tree{
 public Node root = null;

 void insertNodeSorted(Node x, Node tree) {
    if (x.val < tree.val) {
        if (tree.left == null) {
            tree.left = x;
        }
        else
            insertNodeSorted(x, tree.left);
    }
    else {
        if (tree.right == null) {
            tree.right = x;
        }
        else
            insertNodeSorted(x, tree.right);
    }
} // end insertNodeSorted


void deleteNodeSorted(Node x) {
    if (root == null)
        return;
    else
        root = deleteNodeSorted(x, root);
}
Node deleteNodeSorted(Node x, Node tree) {
    if (x.val < tree.val)
        tree.left = deleteNodeSorted(x, tree.left);
    else if (x.val > tree.val)
        tree.right = deleteNodeSorted(x, tree.right);
    else
        tree = replaceNodeSorted(tree);
    return tree;
} // end deleteNodeSorted

// Additional Method
Node replaceNodeSorted(Node tree) {
    if (tree.right == null)
        tree = tree.left;
    else if (tree.left == null)
        tree = tree.right;
    else
        tree.right = findReplacement(tree.right, tree);
    return tree;
} // end replaceNodeSorted
Node findReplacement(Node tree, Node replace) {
    if (tree.left != null)
        tree.left = findReplacement(tree.left, replace);
    else {
        replace.val = tree.val;
        tree = tree.right;
    }
    return tree;
} // end findReplacement

And I'd like to compile the Tree, but I don't know what I exactly I need to write in the main method.

public static void main(String[] args){

  Tree t = new Tree();
  t.insertNodeSorted();

What do I have to write in the brackets in order to print the Tree? (I know I still have to add System.out.println(val); in the methods..)

You defined a variable holding the root node, so it is not necessary to pass the parameter tree for the method insertNodeSorted . You can use always the root node.

Add a method taking only one parameter.

public void insertNodeSorted(Node x) {
    if (root == null) {    
        root = x;
        return;
    }
    insertNodeSorted(x, root);
} 

Define the other method with two parameters as private

 private void insertNodeSorted(Node x, Node tree) {
     ...
 }

Now you can insert elements as follow:

Tree t = new Tree();
t.insertNodeSorted(new Node(1));
t.insertNodeSorted(new Node(134));
t.insertNodeSorted(new Node(13));
t.insertNodeSorted(new Node(4));
...

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