博客
关于我
【java】222. 完全二叉树的节点个数-----了解数据结构,快速了解完全树!
阅读量:360 次
发布时间:2019-03-04

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

给出一个完全二叉树,求出该树的节点个数。

说明:

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例:

输入:

1
/
2 3
/ \ /
4 5 6

输出: 6

方法一:

简单粗暴,每个结点都遍历一次,用时比较长,不过思路很清晰!

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

方法二:

获取左右子树的深度。左子树深度 hl ,右子树深度 hr。

有以下两种可能:

1.hl == hr:左子树为满二叉树,直接计算左子树的节点数,然后继续递归右子树。

2.hl > hr:右子树为满树(相比左子树少了一层),直接计算右子树的节点数,然后继续递归左子树。

public int countNodes(TreeNode root) {           if(root == null) return 0;                int hl = depth(root.left);        int hr = depth(root.right);        if(hl == hr) {               return   (int)Math.pow(2,hl)+ countNodes(root.right);         } else {               return   (int)Math.pow(2,hr) + countNodes(root.left);         }    }        private int depth(TreeNode node) {           int d = 0;        while(node != null) {               node = node.left;            d ++;        }                return d;    }

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

你可能感兴趣的文章
Memcached:Node.js 高性能缓存解决方案
查看>>
memcache、redis原理对比
查看>>
memset初始化高维数组为-1/0
查看>>
Metasploit CGI网关接口渗透测试实战
查看>>
Metasploit Web服务器渗透测试实战
查看>>
Moment.js常见用法总结
查看>>
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>
MongoDB学习笔记(8)--索引及优化索引
查看>>
ms sql server 2008 sp2更新异常
查看>>
MS UC 2013-0-Prepare Tool
查看>>
msbuild发布web应用程序
查看>>
MSCRM调用外部JS文件
查看>>
MSEdgeDriver (Chromium) 不适用于版本 >= 79.0.313 (Canary)
查看>>
msf
查看>>
MSSQL数据库查询优化(一)
查看>>
MSSQL日期格式转换函数(使用CONVERT)
查看>>
MSTP多生成树协议(第二课)
查看>>
MSTP是什么?有哪些专有名词?
查看>>
Mstsc 远程桌面链接 And 网络映射
查看>>
Myeclipse常用快捷键
查看>>