Middle-题目95:222. Count Complete Tree Nodes
来源:互联网 发布:中国人工智能协会 编辑:程序博客网 时间:2024/06/05 19:18
题目原文:
Given a complete binary tree, count the number of nodes.
题目大意:
给出一个完全二叉树,求节点数。
题目分析:
如果直接递归数节点,会超时。所以要考虑完全二叉树的性质:左右子树都是完全二叉树。所以分别求左右子树高度,如果相等则为满二叉树,如果不等则递归统计左右子树即可。
源码:(language:java)
public class Solution { public int countNodes(TreeNode root) { if(root == null) return 0; else { int leftHeight = 0,rightHeight = 0; TreeNode left = root,right = root; while(left!=null) { left=left.left; leftHeight++; } while (right!=null) { right = right.right; rightHeight++; } if(leftHeight == rightHeight) // full binary tree //return (int) (Math.pow(2, leftHeight)-1); return (2<<(leftHeight-1)) - 1; else return 1+countNodes(root.left)+countNodes(root.right); } }}
成绩:
112ms,beats 59.26%,众数116ms,3.89%
cmershen的碎碎念:
其实完全二叉树还有一个性质,就是左右子树至少有一个是满二叉树。这样的话只需要一个递归即可。
0 0
- Middle-题目95: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**
- WebAPI (MVC)Windows Server 2008 IIS部署404错误的解决办法
- 【算法笔记】回溯法——n皇后问题
- C++的重载、覆盖和隐藏(转载)
- Middle-题目94:322. Coin Change
- JAVA 语言的发展简史
- Middle-题目95:222. Count Complete Tree Nodes
- JQuery中元素的数据存储
- springmvc+spring配置
- highcharts中从后台获取数据并添加
- 动态数组类
- 突破限制爬取网页数据 googlesholar为例【转】
- SmbFile 类实现局域网文件共享读写
- 深复制体验
- 1079. Total Sales of Supply Chain (25)