222. Count Complete Tree Nodes
来源:互联网 发布:人民银行金融数据 编辑:程序博客网 时间:2024/06/07 20:00
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
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.
利用完全二叉树的性质。首先求整棵树的高度。然后分两种情况考虑:
第一种,右子树的高度和整棵树的高度相等,也就是右子树到达树的最底部。此时,左子树一定是满的,所以无需遍历左子树,可用公式直接计算出左子树的节点个数。然后递归求解右子树的节点个数。
第二种,右子树的高度小于整棵树的高度,即右子树的高度等于整棵树的高度减一。此时,右子树一定是满的,无需遍历右子树,直接用公式计算出右子树的个数。然后递归求解左子树的节点个数。
程序如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int countNodes(TreeNode root) { if(root == null) { return 0; } return bs(root, 1, getHeight(root)); } // 递归求解树的高度 public int getHeight(TreeNode root) { if(root == null) { return 0; } int height = 1; while(root.left != null) { root = root.left; height++; } return height; } // l代表当前为第几层 // h表示整棵树的高度 public int bs(TreeNode root, int l, int h) { if(root == null) { return 0; } int level = getHeight(root.right) + l; if(level == h) { // 第一种情况 return (1 << (h - l)) + bs(root.right, l + 1, h); }else { // 第二种情况 return (1 << (h - 1- l)) + bs(root.left, l + 1, h); } }}
阅读全文
0 0
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes**
- 222. Count Complete Tree Nodes
- AJAX 基础理论学习笔记
- Python-learning-SMACH-Notes
- apache+mod_jk+tomcat集群配置要点
- 排序算法--对公司员工年龄的排序
- 基于STM32 HAL库在Makefile+GCC-ARM上面的工程编译
- 222. Count Complete Tree Nodes
- 不能在本机启动SQL Server服务 错误代码13
- 关于adb shell procrank提示procrank: not found的问题解决
- Kotlin开发Android系列文章(一)——初识Kotlin
- 开发中碰到的问题:token null is not valid; is your activity running?
- Maven学习总结(22)——Maven settings.xml配置解读
- Android Animation动画原理源码分析(内容已经转移到另一篇)
- zabbix 邮件报警简单配置
- 20170519@静态导入