栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

力扣算法 Java 刷题笔记【二叉树篇】hot100(十一)如何计算完全二叉树的节点数 及其时间复杂度分析 3

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣算法 Java 刷题笔记【二叉树篇】hot100(十一)如何计算完全二叉树的节点数 及其时间复杂度分析 3

文章目录
  • 1. 普通二叉树节点个数
  • 2. 满二叉树节点个数
  • 3. 完全二叉树的节点个数

1. 普通二叉树节点个数

地址: https://labuladong.gitee.io/algo/2/18/31/
2021/12/15
做题反思:

int countNodes(TreeNode root){
	if (root == null) {
		return 0;
	}
	return countNodes(root.left) + countNodes(root.right) + 1;
}

时间复杂度 O(N):

2. 满二叉树节点个数

地址: https://labuladong.gitee.io/algo/2/18/31/
2021/12/15
做题反思:

public int countNodes(TreeNode root) {
	int h = 0;
	while (root != null) {
		root = root.left;
		h++;
	}
	return (int)Math.pow(2, h) - 1;
}
3. 完全二叉树的节点个数

地址: https://leetcode-cn.com/problems/count-complete-tree-nodes/
2021/12/15
做题反思:两个小问题

  1. = 和 ==
  2. if 和 while
class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        TreeNode l = root, r = root;
        int lh = 0, rh = 0;
        while (l != null) {
            l = l.left;
            lh++;
        }
        while (r != null) {
            r = r.right;
            rh++;
        }
        if (rh == lh) {
            return (int)Math.pow(2, lh) - 1;
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
}

这个算法的时间复杂度是 O(logN*logN)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/666866.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号