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

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

Description:

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

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 2hnodes inclusive at the last level h.

思路:给一颗完全二叉树求其节点的个数。首先要明确完全二叉树的定义:把满二叉树从上到下,从左到右进行编号,完全二叉树是其中编号没有断续的部分。也就是说完全二叉树只可能在最右子树的叶子节点的位子上有空缺。而且左右子树的高度差不能大于1。所以只要是count(左节点)==count(右节点)那么就是一颗满二叉树。可以用公式计算出节点的个数NodeCount=2^h - 1。若不是满二叉树的话就递归遍历求count(左子树) + count(右子树) + 1。

/** * 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;        TreeNode left = root, right = root;        int leftCount = 0;        while(left!= null) {            left = left.left;            leftCount ++;        }        int rightCount = 0;        while(right != null) {            right = right.right;            rightCount ++;        }        if(leftCount==rightCount) {            return (2<<(leftCount-1)) - 1;        } else {            return countNodes(root.left) + countNodes(root.right) + 1;        }    }        }

  

转载于:https://www.cnblogs.com/wxisme/p/4728765.html

你可能感兴趣的文章
wiquery ResizePanel 2
查看>>
Windows 下 Qt Creator 5.3.1 环境构建
查看>>
git 搭建多人开发环境
查看>>
ubuntu升级 openssh
查看>>
在上海麦迪广告有限公司 做工作的工作项目
查看>>
【ZZ】互联网协议入门(二)
查看>>
swift遇见的坑 和 第三方库资源
查看>>
get post 区别
查看>>
c:forEach使用索引
查看>>
将Java程序作成exe文件的N种方法
查看>>
Ubuntu 12.04 LTS建立内核树(2)
查看>>
python 之第三方插件安装
查看>>
设置IP地址的技巧
查看>>
android图片文件的路径地址与Uri的相互转换
查看>>
java.security包实现对象加密
查看>>
李学江:B2B行业门户网站最终页标题设置方法
查看>>
心空空的,说不清感觉
查看>>
php版快速排序
查看>>
java数组之间区别
查看>>
cacti install
查看>>