计算树的后代(子节点)

时间:2014-05-04 19:45:48

标签: java recursion tree

我有以下树结构,节点是第一个子节点和下一个兄弟节点

public class Node 
{
 public Node firstChild;
 public Node nextSibling;
}

我正在尝试编写一个可以计算节点所有后代的函数。我只是想知道我的方法是否正确

public int descendentsCount (Node node)

  {

    if(node.firstChild == null && node.nextSibling ==null)
    return 0;

    else if(node.firstChild == null && node.nextSibling!=null)
    node = node.nextSibling;

    count ++; // count is static 

    descendentsCount(node.firstChild);
    return count;

  }

2 个答案:

答案 0 :(得分:1)

public static int descendentsCount (Node node) {
    if (node == null)
        return 0;
    return subTreeCount(node) - 1; // exclude node from count
}

// counts nodes in subtree (including node)
public static int subTreeCount(Node node) {
    if (node == null) {
         return 0;
    }
    int count = 1; // include node in count

    // add subtree sizes of all children
    Node child = node.firstChild;
    while (child != null) {
        count += subTreeCount(child);
        child = child.nextSibling;
    }
    return count;
}

答案 1 :(得分:0)

 public static int descendentsCount(Node node)
    {
        if (node == null)
        {
          return 0;
        }
        return subTreeCount(node.firstChild);
    }

    public static int subTreeCount(Node node)
    {
        // base case 
        if (node == null)
        {
            return 0;
        }

        // process all children and siblings
        return 1 + subTreeCount(node.firstChild) + subTreeCount(node.nextSibling);
    }