SteelCrow
SteelCrow

Reputation: 3

Find child in non-binary tree (recursively)

I have TreeNode class - implementation of the node of the non-binary tree (List<TreeNode> children).

I need find the first node with the given data among the children of this. I wrote some method, but there is some problem obviously (java.lang.AssertionError: Failed to find a child with not-null data: expected:<2> but was:<null>). (if data is null I need to return first child with null data).

public TreeNode findChild(Object data) {


    if (data == null) {
        Iterator<TreeNode> a = getChildrenIterator();
        TreeNode tmp;
        while (a.hasNext()) {
            tmp = a.next();
            if (tmp.getData()==null) return tmp;
            tmp.findChild(data);
        }
    }else
    {
        Iterator<TreeNode> a = getChildrenIterator();
        TreeNode tmp;
        while (a.hasNext()) {
            tmp = a.next();
            if (data.equals(tmp.getData())) return tmp;
            tmp.findChild(data);
        }
    }

    return null;
}

Upvotes: 0

Views: 1661

Answers (2)

Robert Kock
Robert Kock

Reputation: 6018

The problem is within the fact you don't return the result of the recursive call. Maybe the following code will help:

import java.util.*;

public class TreeNode
{
  // Constructor
  public TreeNode()
  {
   children = new ArrayList<TreeNode>();
   node_data = null;
  }

  // Get node's data
  public Object getData()
  {
    return (node_data);
  }

  // Set node's data
  public void setData(Object data)
  {
    node_data = data;
  }

  // Find the node with specified data
  // Return null if not found
  public TreeNode findChild(Object data)
  {
    // Maybe we're the one we're looking for
    if (equalData(data))
      return (this);

    // Search within child nodes
    Iterator<TreeNode> it;
    TreeNode           node;
    it = getChildrenIterator();
    while (it.hasNext())
    {
      node = findChild(it.next());
      if (node != null)
        return (node);
    }

    // If we get here, we didn't find it
    return (null);

  } // findChild

  // Return whether specified data equals ours
  private boolean equalData(Object data)
  {
    if (node_data == null)
      return (data == null);
    else
      return (node_data.equals(data));
  }

  // Return iterator over node's children
  private Iterator<TreeNode> getChildrenIterator()
  {
    return (children.iterator());
  }

  // The node's children
  private List<TreeNode> children;

  // The node's data
  private Object node_data;

} // class TreeNode

Upvotes: 0

user207421
user207421

Reputation: 310913

Your recursion isn't correct. You should be returning the result of tmp.findChild() if it returns a non-null value.

You also need to consider whether you're supposed to be implementing a depth-first or breadth-first search.

Upvotes: 1

Related Questions