计算二叉树中叶节点的数量 [英] counting number of leaf nodes in binary tree

查看:181
本文介绍了计算二叉树中叶节点的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要计算叶子节点的数量: 注意:不能使用全局/类级别的变量 我遵循了算法,但效果很好.但是我希望方法签名是

I want to count the no of leaf nodes: Note:Cannot use global/class level variable I implmeted following algo, and it works fine.But i want method signature to be

countLeaves(Node node)

我知道我可以重载方法并从1个args调用2个args方法sig,但是不想这么做.有人可以建议其他方法吗?

I know that i can overload methds and call the 2 args method sig from 1 args, but dont want to do so.Can anyone suggest any other method?

int countLeaves(Node node,int count){
        if(node==null)
            return 0;

        if(node.left==null && node.right==null){
            return 1+count;
        }else{
            int lc = countLeaves(node.left, count);
            int total = countLeaves(node.right, lc);
            return total;
        }
    }

推荐答案

int countLeaves(Node node){
  if( node == null )
    return 0;
  if( node.left == null && node.right == null ) {
    return 1;
  } else {
    return countLeaves(node.left) + countLeaves(node.right);
  }
}

您正在做与以前相同的事情,但是我们只是说返回左节点和右节点之和的结果,而不是像现在那样保留当前计数.这些依次递归向下,直到达到基本情况为止.

You are doing the same thing as before but instead of holding the current count as we go, we simply say return the result of the sum of the left and right node. These in turn recurse down till they hit the basecases.

这篇关于计算二叉树中叶节点的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆