在非二叉树中查找子项(递归)

时间:2016-02-24 08:08:21

标签: java algorithm recursion tree

我有TreeNode类 - 非二叉树(List<TreeNode> children)节点的实现。

我需要在这个孩子中找到第一个带有给定数据的节点。我写了一些方法,但显然存在一些问题(java.lang.AssertionError: Failed to find a child with not-null data: expected:<2> but was:<null>)。 (如果data为null,我需要返回第一个具有空数据的子节点)。

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;
}

2 个答案:

答案 0 :(得分:0)

您的递归不正确。您应该返回 tmp.findChild() 的结果,如果它返回非空值。

您还需要考虑是否应该实施深度优先或广度优先搜索。

答案 1 :(得分:0)

问题在于您不会返回递归调用的结果。 也许以下代码会有所帮助:

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
相关问题