题意

给一棵 complete binary tree,数数看一共有多少个结点。做题链接

直观做法:递归

var countNodes = function(root) {
if(root===null) return 0;
return 1+countNodes(root.left)+countNodes(root.right);
};

老实说,一道难度为 medium 的题目,这么几秒钟的时间就做出来,我心中有一种不真实感。

所以,我看了一下 discuss 区其他人的解法,看是不是我自己想的不够深入。

结果发现,我这个做法没错,就是时间复杂度不够优化,如果这道题要真正成为一道难度为medium的题目,需要限制时间复杂度。

下面是一种据说是 O(log(n)^2) 的解法,很聪明,根据不同树结构选择计算左树结点数或右树节点数,可以省去访问大部分结点的时间。

优化做法:计算树高,观察树结构

var countNodes = function(root) {
let h = height(root);
return h === 0 ? 0 :
height(root.right)=== h-1 ? (1 << (h-1)) + countNodes(root.right) :
                                        (1 << (h-2)) + countNodes(root.left) ;
};
function height(root){
return root === null? 0 : 1+height(root.left);
}

首先,height 函数,没啥好说的,跟普通的计算树高度函数不同点在于,充分利用了 complete binary tree 的特点,更加省事。

其次,要理解根据 root 的高度 和 右子树高度的不同情况的选择。

情况一:

height(root) === 0

这个情况没啥好说的,就是边界情况,啥结点都没有,返回0;

情况二:

height(root.right) === h-1

这个情况就是下面图这种情况,右子树至少最左边有一个结点(这个结点把右子树的高度撑到 h-1):

这种情况下,左子树是完整的,它的节点数是  2^(h-1)-1 ,加上根结点,等于  2^(h-1) ,也就是  1 << (h-1) (图中绿色结点总数)。

情况三:

height(root.right) === h-2

这种情况就是右子树最后一层没有任何结点,左子树至少最后一层最左边有一个结点:

这种情况下,右子树是完整的,它的节点数是  2^(h-2)-1 ,加上根结点,等于  2^(h-2) ,也就是  1<<(h-2) (图中绿色结点总数)。

再次优化:用遍历取代递归

直接遍历所有的节点,可以省下反复计算 height 的不必要的时间。

因为很明显,子树的高度 跟 父树的高度 息息相关。如果通过递归,下一次还得重新计算高度值;而用遍历,直接  h--;  就得到子树高度值。(当然你也可以在递归函数中把高度当成参数传递进去,但是不够简洁,没必要)

var countNodes = function(root) {
let h = height(root), nodes = 0;
while(root!==null){
if(height(root.right)===h-1){
nodes += 1 << (h-1);
root = root.right;
}
else{
nodes += 1 << (h-2);
root = root.left;
}
h--;
}
return nodes;
};
function height(root){
return root===null? 0 : 1+height(root.left);
}

第一种简单方法的优化

最开始我用了一种最简单的方法:

var countNodes = function(root) {
if(root===null) return 0;
return 1+countNodes(root.left)+countNodes(root.right);
};

LeetCode 的 discuss 区看到 一种优化方法:

var countNodes = function(root) {
if(root===null) return 0;
let left = root.left, right = root.right, height = 1;
while(right !== null){
left = left.left;
right = right.right;
height++;
}
if(left === null) return (1 << height)-1;
return 1 + countNodes(root.left) + countNodes(root.right);
};

这种方法其实也是利用了 Complete Binary Tree 的特点,如果一棵树是完整的(就是它所有树叶都处于同一层),那么在 右子树 为  null  之前, left = left.left; right = right.right; 最左最右两个分枝同时向下延伸,最后一定同时抵达树叶。

这种方法的优化之处在于,当遇到的子树的所有树叶都位于同一层时,它会直接返回该子树的结点数。像下面这样的树,当遇到结点 3, 5, 8 时,不会再调用函数递归,而是直接计算出整颗子树的结点数  (1 << height) - 1 。

总结

要了解数据结构的特点,并且充分利用这些特点来省事。

PS:上面全部代码为 JavaScript

【刷题笔记】LeetCode 222. Count Complete Tree Nodes的更多相关文章

  1. [LeetCode] 222. Count Complete Tree Nodes 求完全二叉树的节点个数

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

  2. Java for LeetCode 222 Count Complete Tree Nodes

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

  3. (medium)LeetCode 222.Count Complete Tree Nodes

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

  4. leetcode 222.Count Complete Tree Nodes

    完全二叉树是从左边开始一点点填充节点的,因此需要计算所有的节点的个数. 则分别从左边和右边来进行传递的,当左右是完全二叉树的时候,其节点个数就是pow(2,h)-1. /** * Definition ...

  5. [leetcode]222. Count Complete Tree Nodes完全二叉树的节点数

    /* 满二叉树的特点是2^n-1,对于完全二叉树,一个node如果左右子树深度相同,那么 是一个满二叉树.如果不是,那就把node算上,继续往下看,下边的可能是满二叉树 由于完全二叉树中有一些子满二叉 ...

  6. 【LeetCode】222. Count Complete Tree Nodes 解题报告(Python)

    [LeetCode]222. Count Complete Tree Nodes 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个 ...

  7. leetcode 958. Check Completeness of a Binary Tree 判断是否是完全二叉树 、222. Count Complete Tree Nodes

    完全二叉树的定义:若设二叉树的深度为h,除第 h 层外,其它各层 (1-h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树. 解题思路:将树按照层进行遍历,如果 ...

  8. 【刷题-LeetCode】222. Count Complete Tree Nodes

    Count Complete Tree Nodes Given a complete binary tree, count the number of nodes. Note: Definition ...

  9. LeetCode OJ 222. Count Complete Tree Nodes

    Total Accepted: 32628 Total Submissions: 129569 Difficulty: Medium Given a complete binary tree, cou ...

随机推荐

  1. 了解jQuery的$符号

    $是什么? 可以使用typeof关键字来观察$的本质. console.log(type of $); //输出结果为function 因此可以得出结论,$其实就是一个函数.$(); 只是根据所给参数 ...

  2. 命令模式 Command design pattern in C++

    参考https://sourcemaking.com/design_patterns/command/cpp/2 Create a class that encapsulates some numbe ...

  3. Sublime Text 3 Build 3047 安装/插件安装/C编程环境配置

    Sublime Text 3 Build 3047 安装 参考:http://sublimetext.iaixue.com/forum.php?mod=viewthread&tid=29 插件 ...

  4. Exact Change FreeCodeCamp

    function checkCashRegister(price, cash, cid) { var change; var sumCid = 0; // Here is your change, m ...

  5. 微信小程序打开PDF

    具体情况是:微信小程序打开springboot返回的pdf文件.微信端先downloadFile,然后openDocument.但是打开文档一直不成功.后来发现官网的例子没有加fileType,我在参 ...

  6. Selenium 安装与配置及webdriver的API与定位元素

    1. selenium安装命令行 C:\Users\wu>cd /d E:\soft\python3.6\Scripts E:\soft\python3.6\Scripts>pip3 in ...

  7. 30 包含min函数的栈(举例让抽象问题具体化)

    题目描述: 定义栈的数据结构(push/pop),请在该类型中实现一个能够得到栈中所含最小元素的min函数(三者的时间复杂度都应为O(1)). 测试用例: 1)新压入栈的数字比之前的最小值大/小 2) ...

  8. C++ STL - queue使用详解

    c++队列模板类的定义在<queue>头文件中,queue 模板类需要两个模板参数,一个是元素类型,一个容器类型,元素类型是必要的,容器类型是可选的,默认为deque 类型. 下面详细介绍 ...

  9. 我的第一个arcgis地图应用

    步骤: 1.设置一个基本的html文档 <!DOCTYPE html> <html> <head> <meta http-equiv="Conten ...

  10. Untiy中的数据平滑处理

    本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接:http://blog.csdn.net/cartzhang/article/details/50680237 作者:car ...