首页 > 其他 > 详细

求二叉树中叶子节点的个数

时间:2019-05-11 17:00:57      阅读:190      评论:0      收藏:0      [点我收藏+]

求二叉树中叶子节点的个数

面试题二叉树

题目描述
求二叉树中叶子节点的个数。

叶子节点的定义:如果一个节点既没有左孩子,也没有右孩子,则该节点为叶子节点。

示例:

    3
   /   9  20
    /     15   7

在这个二叉树中,叶子节点有 9,15,7,所以返回 3。

Java 实现

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class Solution {
    public int getLeafCount(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            // 输出叶子节点
            System.out.println("leaf nodes:" + root.val);
            return 1;
        }
        return getLeafCount(root.left) + getLeafCount(root.right);
    }
}
public class Test {
    public static void main(String[] args) {
        Solution tree = new Solution();
        /* create a tree */
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(tree.getLeafCount(root));
    }
}

运行结果

leaf nodes:9
leaf nodes:15
leaf nodes:7
3

参考资料

求二叉树中叶子节点的个数

原文:https://www.cnblogs.com/hglibin/p/10849173.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!