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.
题意:给定一棵完全二叉树,计算节点数目。
分类:二叉树
解法1:完全二叉树的定义是,除最后一层外,每一层上的节点数均达到最大值;在最后一层上只缺少右边的若干结点。
完全二叉树的一个特殊例子是满二叉树。
如果一棵树是满二叉树,那么我们可以用公式2^k-1计算它的节点数目。
如果不是满二叉树,我们要分别计算左子树和右子树,这是一个递归过程,最好左右子树和+1,为结果
根据上面的说法,我们可以先通过查找最左边节点的个数,最右边节点的个数
如果这两个数目相同,就是满二叉树,可以通过公式直接返回
如果不同,则递归分别计算左右子树的数目
原文链接http://blog.csdn.net/crazy__chen/article/details/47189559