博客
关于我
【java】222. 完全二叉树的节点个数-----了解数据结构,快速了解完全树!
阅读量:360 次
发布时间:2019-03-04

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

给出一个完全二叉树,求出该树的节点个数。

说明:

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例:

输入:

1
/
2 3
/ \ /
4 5 6

输出: 6

方法一:

简单粗暴,每个结点都遍历一次,用时比较长,不过思路很清晰!

public int countNodes(TreeNode root) {           if(root == null) return 0;        return countNodes(root.left) + countNodes(root.right) + 1;    }

方法二:

获取左右子树的深度。左子树深度 hl ,右子树深度 hr。

有以下两种可能:

1.hl == hr:左子树为满二叉树,直接计算左子树的节点数,然后继续递归右子树。

2.hl > hr:右子树为满树(相比左子树少了一层),直接计算右子树的节点数,然后继续递归左子树。

public int countNodes(TreeNode root) {           if(root == null) return 0;                int hl = depth(root.left);        int hr = depth(root.right);        if(hl == hr) {               return   (int)Math.pow(2,hl)+ countNodes(root.right);         } else {               return   (int)Math.pow(2,hr) + countNodes(root.left);         }    }        private int depth(TreeNode node) {           int d = 0;        while(node != null) {               node = node.left;            d ++;        }                return d;    }

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

你可能感兴趣的文章
MySQL分组查询
查看>>
Mysql分表后同结构不同名称表之间复制数据以及Update语句只更新日期加减不更改时间
查看>>
mySql分页Iimit优化
查看>>
MySQL分页查询
查看>>
WebDriverException:未知错误:对于旧版本的 Google Chrome,在 Python 中找不到带有 Selenium 的 Chrome 二进制错误
查看>>
mysql列转行函数是什么
查看>>
mysql创建函数报错_mysql在创建存储函数时报错
查看>>