0

I am new to data structures and binary trees so I am a little bit lost . My problem is that how do we insert values in the tree itself ?

1
  • Is this homework? If so, you should mark it with the [homework] tag. Commented Apr 23, 2012 at 16:31

3 Answers 3

1

You just need to check for this case explicitly.

Update

Also you'll need to add another Add(int v) method for public use (you can also make you current Add(Node, int) private).

public void Add(int v) {
    if (root == null) {
        // creating root node if it doesn't exist
        root = new Node();
        root.setValue(v);
    } else {
        // adding new element to tree
        Add(root, v);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

so in the Add method when i do t.setRight(v); or t.setLeft(v); i get an error saying that it can't be applied to given types because v is an int while setRight and setLeft only accept Node parammeters , so how can i fix this problem ?
Got it. Your current Add method should be private (because it expose implementation detail Node t to public). And you should add new Add(int v) method. See my updated answer.
0

Add a new node like this:


Node n1 = new Node();
Node n2 = new Node();
n1.setValue(1);
n2.setValue(2);
n1.setRight(n2);

Comments

0

You want to pass root at the start. You can just overload Add:

public void Add(int v) {
    Add(root, v);
}

And you'll need to special case the situation where root == null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.