开发者

non void method for binary tree inorder traversal

开发者 https://www.devze.com 2023-04-09 09:26 出处:网络
I\'m wondering if its possible to have an inorder tree traversal method in java actually RETURN something... I\'m trying to traverse through the tree given a node and a value, return the node that mat

I'm wondering if its possible to have an inorder tree traversal method in java actually RETURN something... I'm trying to traverse through the tree given a node and a value, return the node that matches the value:

/**
 * Variable for storing found node from inorder search
 */
private Node returnNode; 


/**
 * Perform an inorder search through tree.
 * If a value is matched, the node is saved to returnNode, otherwise 开发者_Go百科return null.
 * @param node The given node
 * @param value The value of the node to be found.
 */
public void inorder(Node node, Object value){
    if(node != null){
        inorder(node.leftChild, value);
        if(node.value.equals(value)){
            System.out.println(value + " was found at " + node);
            returnNode = node;
        }
        inorder(node.rightChild, value);
    }
}

Right now, I've tried declaring a public node to store the value, but I find that that doesn't work when I run:

assertEquals(newNode3, BT.contains("3"));
assertEquals(null, BT.contains("abcd"));

Where returnNode takes on newNode3's values and messes up my tests for null.

Can anyone point me in the right direction?


I would have thought you'd want something like this:

/**
 * Perform an inorder search through tree.
 * The first node in order that matches the value is returned, otherwise return null.
 * @param node The given node
 * @param value The value of the node to be found.
 * @return The first node that matches the value, or null
 */
public Node inorder(Node node, Object value){
    Node result = null;
    if(node != null){
        result = inorder(node.leftChild, value);
        if( result != null) return result;

        if(node.value.equals(value)){
            System.out.println(value + " was found at " + node);
            return node;
        }
        result = inorder(node.rightChild, value);
    }
    return result;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号