计算通用树中叶节点的数量

时间:2015-07-12 19:59:12

标签: java

我很确定我的逻辑是正确的,但我得到了错误的答案 请在不改变程序逻辑的情况下指出错误。

public static int countLeaves(TreeNode<Integer> root,int max)
    {
// TODO Auto-generated method stub
        if(root==null)
        {
            return 0;
        }
        if(root.children.size()==0)
        {
            return 1;
        }

        for(int i = 0; i < root.children.size(); i++) 
        {
            max = max + countLeaves(root.children.get(i),max);
        }

        return max;
    }
public static void main(String[] args) {
        // TODO Auto-generated method stub

        TreeNode<Integer> root = takeInputLevelWise();
        printTree(root);
        int max = 0;

        System.out.println(countLeaves(root, max));
}

3 个答案:

答案 0 :(得分:1)

您的逻辑不正确所以我无法在不改变您的逻辑的情况下指出您的错误: - )

问题是重复计算,在这里:

    for(int i = 0; i < root.children.size(); i++) 
    {
        max = max + countLeaves(root.children.get(i),max);
    }

也就是说,您向下传递max(这是到目前为止的叶数),添加,然后返回它,再次添加

从设计角度考虑它。到目前为止,为什么countLeaves甚至需要知道你的数量? countLeaves应该只返回它下面的叶子数量,对吗? max无需传递。

public static int countLeaves(TreeNode<Integer> root)
    {
// TODO Auto-generated method stub
        int leaves = 0;
        if(root==null)
        {
            return 0;
        }
        if(root.children.size()==0)
        {
            return 1;
        }

        for(int i = 0; i < root.children.size(); i++) 
        {
            leaves += countLeaves(root.children.get(i));
        }

        return leaves;
    }
public static void main(String[] args) {
        // TODO Auto-generated method stub

        TreeNode<Integer> root = takeInputLevelWise();
        printTree(root);

        System.out.println(countLeaves(root));
}

答案 1 :(得分:0)

Python 中计算泛型树中叶节点数的代码是

def leafNodeCount(tree):
if len(tree.children) == 0:
    return 1
Num = 0
for child in tree.children:
    Num += leafNodeCount(child)
return Num

答案 2 :(得分:-1)

public static int countLeaves( TreeNode<Integer>root ) {
      if( root == null ){
         return 0;
      }

       if( root.children.size() = 0 ) {
          return 1;
       }

      int count = 0;
      for( TreeNode<Integer>child : root.children ) {
          count += countLeaves(child);
      }

      return count;
}