【问题标题】:Determining if a node in a tree is full确定树中的节点是否已满
【发布时间】:2012-11-03 18:00:01
【问题描述】:

我正在尝试确定 m-ary 树中的所有节点是否已满。我想我有大致的想法,但我不确定。这是我到目前为止所做的。

在我的 TreeNode 类中,我有以下方法。

    public class TreeNode
    {
       private String label;
       private String message;
       private TreeNode[] nodes;
       private int numChildren;
       private TreeNode parent;
       private String prompt;

           ***other methods and constructors***

      public boolean isFull()
    {
      for(int i = 0; i < numChildren; ++i)
      {
        if(nodes[i] == null)
            return false;
      }
      return true;
    }

其中 numChildren 是数组 nodes[](或只是 nodes.length)中可能的子节点总数,nodes[] 是当前节点的所有子节点的数组。 此外,知道我的 TreeNode 是双向链接的可能会有所帮助,因此如果需要,我可以检索当前节点的父节点。

然后,在我的 Tree 类中,我有以下递归方法。

    public boolean allNodesFull(TreeNode n)
    {
      boolean allFull = false;
      if(!n.isFull())
      {
        return allFull;
      }
      for (int i = 0; i < n.getNumChildren(); ++i)
      {
        allFull = allNodesFull(n.getChild(i));
      }
      return allFull;
    }

【问题讨论】:

  • 现在的allFull 永远不可能是true

标签: java recursion tree nodes


【解决方案1】:

尚未测试,希望您已经准备好测试用例并告诉我们它是否有效;)

public boolean allNodesFull(TreeNode n) {
  if(!n.isFull()) {
    return false;
  }
  for (int i = 0; i < n.getNumChildren(); ++i) {
    if (!allNodesFull(n.getChild(i))) {
      return false;
    }
  }
  return true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    相关资源
    最近更新 更多