How to find a node in a Tree Java

user395817 :

I am a beginner in Java and I am currently trying to solve an exercise in Trees chapter.

A tree is made up of these nodes. enter image description here. A node holds a value that corresponds to an integer. Apart from the node at the root of the tree, a node always has only one other node that references it. If a node has no child to the right or to the left, then the corresponding reference is null. the value held by any child in the subtree on the left is less than the value of his parent and the value held by any child in the subtree on the right is greater than the value of his parent. the height of the tree is between 0 and 100 000 knots.

I am trying to implement a find(int v) method that returns the node holding the value v if the node does not exist then find will have to return null.

This is what I've done till know but i'm a little bit lost :

class Node{
    Node left, right;
    int value;

    public Node find (int v){
        Node result = null;
        if (this.left != null) result = find(v);
        if (this.value == v) return this;
        if (result == null && this.right != null) 
            result = find(v);

        return result;     

    }

    public static void main (String[] args){
        Node n = smallNode.find(8);
        System.out.println(n);
        n = LargestNode.find(0);
        System.out.println(n);
    }
}

I am getting a StackoverOverflowError at this line :

if (this.left != null) result = find(v);

What am i doing wrong ? I can't find why it is rising this exception.

RAZ_Muh_Taz :

You should check the value first, return this if the node has the value you are looking for. If it doesn't check you can continue from the current node and go right, once you have returned check the result with the given value, if correct return that Node, otherwise return whatever the left side gives. It will either be the Node with the value you want or null.

public Node find (int v){
    Node result = null;

    //check for value first
    if (this.value == v) return this;

    //check if you can go any further from the current node
    if(this.left == null && this.right == null) return null;

    //now go right
    result = this.right.find(v);

    //check the node
    if(result != null && result.value == v) return result;

    //if not found return whatever is returned by searching left
    return this.left.find(v);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=100072&siteId=1