博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 222. Count Complete Tree Nodes
阅读量:7026 次
发布时间:2019-06-28

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

Problem

Given a complete binary tree, count the number of nodes.

Note:

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.

Example:

Input:     1   / \  2   3 / \  /4  5 6Output: 6

Solution

class Solution {    public int countNodes(TreeNode root) {        if (root == null) return 0;        int height = 0;        TreeNode left = root.left, right = root.right;        while (left != null && right != null) {            height++;            left = left.left;            right = right.right;        }        if (left == null && right == null) return (1 << (height+1)) - 1;        else return 1 + countNodes(root.left) + countNodes(root.right);    }}

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

你可能感兴趣的文章
V-4-3 访问vCenter与操作
查看>>
运维DBA的4大纪律9项注意【转】
查看>>
写python的常用工具及设置
查看>>
PLSQL Developer软件使用大全
查看>>
PHP5.3.3添加安装mcrypt模块
查看>>
salt-minion自动化安装脚本
查看>>
给硬盘加密
查看>>
【CDN 常见问题】CDN协议跟随回源常见问题
查看>>
带账号、密码ssh的脚本
查看>>
Exchange Server 2010客户端的安全访问
查看>>
申请带@msn.com后缀的邮箱
查看>>
服务器断电导致虚拟机数据丢失怎么恢复?
查看>>
Android官方开发文档Training系列课程中文版:连接无线设备之网络服务搜索功能...
查看>>
浅撸 css3 flex 布局
查看>>
域用户和工作组
查看>>
模拟器与真机的程序差别J2ME
查看>>
vsftpd基于数据库文件实现虚拟用户管理站点目录
查看>>
静态成员和实例成员
查看>>
robotframework中文日志显示乱码
查看>>
Unit 12 电话留言
查看>>