获取二叉树叶子结点个数
[!Tip]
本节源代码见Github链接🔗
问题描述
获取二叉树叶子结点个数
核心思路
层序遍历二叉树,既无左子结点也无右子结点的结点为叶子结点
实现代码
【👉🏻>>点击展开查看代码】
/**
* 计算二叉树中叶子结点个数
*
* @className: NumberOfLeavesInBT
* @author: Max Solider
* @date: 2023-06-11 19:29
*/public class NumberOfLeavesInBT {
public static int numberOfLeavesInBT(BinaryTreeNode root) {
if (root == null) {
return 0;
}
int count = 0;
ArrayQueue queue = new ArrayQueue(10);
queue.enQueue(root);
while (!queue.isEmpty()) {
BinaryTreeNode tmp = (BinaryTreeNode) queue.deQueue();
if (tmp.getLeft() == null && tmp.getRight() == null) {
count ++;
}
if (tmp.getLeft() != null) {
queue.enQueue(tmp.getLeft());
}
if (tmp.getRight() != null) {
queue.enQueue(tmp.getRight());
}
}
return count;
}
}
时间复杂度
时间复杂度为O(n)。
空间复杂度
空间复杂度为O(n)。