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

力扣 222. 完全二叉树的节点个数

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

力扣 222. 完全二叉树的节点个数

最近开始刷力扣,将每日做题心得都会发布在这上面,以便日后查看。

起初看到这个题,忘记了完全二叉树的概念是什么,于是回顾一下。

这里参考了以下链接

满二叉树、完全二叉树、平衡二叉树、最优二叉树

时间复杂度:O(logn * logn)

空间复杂度:O(1)

class Solution {
    public int countNodes(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftDepth = getDepth(root.left);
        int rightDepth = getDepth(root.right);
        if(leftDepth == rightDepth){
            //左子树为满树,递归右子树
            return countNodes(root.right) + (1 << leftDepth);
        }else{
            //右子树为满树,递归左子树
            return countNodes(root.left) + (1 << rightDepth);
        }


    }

    //得到树的深度
    public int getDepth(TreeNode node){
        TreeNode root = node;
        int depth = 0;
        while(root != null){
            depth++;
            root = root.left;
        }
        return depth;
    }

}

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

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

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