博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode222. Count Complete Tree Nodes (思路及python解法)
阅读量:2241 次
发布时间:2019-05-09

本文共 804 字,大约阅读时间需要 2 分钟。

Given a complete binary tree, count the number of nodes.

Note:

Definition of a complete binary tree from :

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example:

Input:     1   / \  2   3 / \  /4  5 6Output: 6

有很多种方法,直接用bfs算法统计每层个数即可。

class Solution:    def countNodes(self, root: TreeNode) -> int:        if root is None:return 0        bfs=[root]        sums=0        while bfs:            sums+=len(bfs)            temp=[]            for node in bfs:                if node.left:                    temp.append(node.left)                if node.right:                    temp.append(node.right)            bfs=temp        return sums

 

转载地址:http://kjrbb.baihongyu.com/

你可能感兴趣的文章
用学习曲线 learning curve 来判别过拟合问题
查看>>
用验证曲线 validation curve 选择超参数
查看>>
用 Grid Search 对 SVM 进行调参
查看>>
用 Pipeline 将训练集参数重复应用到测试集
查看>>
PCA 的数学原理和可视化效果
查看>>
机器学习中常用评估指标汇总
查看>>
什么是 ROC AUC
查看>>
Bagging 简述
查看>>
详解 Stacking 的 python 实现
查看>>
简述极大似然估计
查看>>
用线性判别分析 LDA 降维
查看>>
用 Doc2Vec 得到文档/段落/句子的向量表达
查看>>
使聊天机器人具有个性
查看>>
使聊天机器人的对话更有营养
查看>>
一个 tflearn 情感分析小例子
查看>>
attention 机制入门
查看>>
手把手用 IntelliJ IDEA 和 SBT 创建 scala 项目
查看>>
GAN 的 keras 实现
查看>>
AI 在 marketing 上的应用
查看>>
Logistic regression 为什么用 sigmoid ?
查看>>