繁体   English   中英

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

[英]Find child in non-binary tree (recursively)

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

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

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

您还需要考虑应该执行深度优先搜索还是广度优先搜索。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM