LeetCode 222 Count Complete Tree Nodes
2015-12-11 08:52
513 查看
题目描述
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.
分析
如果层序遍历,时间复杂度是O(n)。可以使用类似二分查找的方法,因为二叉树是完全二叉树,计算leftHeight和rightHeight,最大相差1,然后递归求解。代码
[code] public int countNodes(TreeNode root) { if (root == null) { return 0; } int leftHeight = 0; int rightHeight = 0; // 计算leftHeight TreeNode p = root; while (p != null) { p = p.left; leftHeight++; } // 计算rightHeight p = root; while (p != null) { p = p.right; rightHeight++; } // 如果相等,满足2^n-1 if (leftHeight == rightHeight) { return (1 << leftHeight) - 1; } return 1 + countNodes(root.left) + countNodes(root.right); }
相关文章推荐
- node包管理器npm 学习笔记(5)
- Remove Nth Node From End of List
- Insert Node in a Binary Search Tree
- 简述CCNode和Sprite的渲染过程
- hadoop mkdir: Cannot create directory /usr. Name node is in safe mode.
- nodejs 操作文件(文件夹)
- NodeJS 基本操作
- Nodejs源码解析之module
- nodejs入门
- yum node.js
- node.js中模块,require
- C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)
- node开发环境搭建(windows)
- 理解Node.js的事件循环
- nodejs项目在webstorm里进行debug的设定
- nodejs获取当前url和url参数值
- NODE 安装express4.X 失败
- node.js入门总结
- wix xslt for adding node
- leetcode:237 Delete Node in a Linked List-每日编程第四题