码迷,mamicode.com
首页 > 其他好文 > 详细

计算完全二叉树所有节点数

时间:2015-07-14 22:22:12      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:

  今天在leetcode,遇见一个题目,计算一个完全二叉树所有的节点数。这里分享一下心得。

  首先,需要完全掌握什么是完全二叉树?

  我觉得对于完全二叉树的概念中,有一点需要注意。完全二叉树:除最后一层外,每一层上的节点数均达到最大值;在最后一层上只缺少右边的若干结点。最后一层的结点一定是向左靠。其主要思想是,想以某一个结点为“根结点”,然后,然后判断其是否是满二叉树,因为满二叉树是计算很简单2- 1(k=1,2,3```),即对于满二叉树只需要计算出其深度即可,也就是利用满二叉树简化对完全二叉树的计算。当然,还有一种很简单的方法,就是遍历每一个结点,在遍历的同时进行计数,明显这不是一个好方法。

 


  首先,贴出的是python的实现方式。

 

 1 class TreeNode:
 2     def __init__(self, x):
 3         self.val = x
 4         self.left = None
 5         self.right = None
 6 
 7 class Solution:
 8     # @param {TreeNode} root
 9     # @return {integer}
10     def __init__(self):
11         self.count = 0
12 
13     def countNodes(self, root):
14         if not root:
15             return 0
16         lDepth = self.getDepth(root.left)
17         rDepth = self.getDepth(root.right)
18         if lDepth == rDepth:
19             return (1 << lDepth)+self.countNodes(root.right)
20         else:
21             return (1 << rDepth)+self.countNodes(root.left)
22 
23     def getDepth(self, root):
24         depth=0
25         node = root
26         while node:
27             node = node.left
28             depth += 1
29     
30         return depth

 


  接下来,是C语言实现此算法,思路和上面是完全一样的。

 1  struct TreeNode {
 2      int val;
 3     struct TreeNode *left;
 4     struct TreeNode *right;
 5 };
 6 
 7 int countNodes(struct TreeNode* root) {
 8     int ldepth, rdepth;
 9 
10     if(root == NULL){
11         return 0;
12     }
13 
14     ldepth = getDepth(root->left);
15     rdepth = getDepth(root->right);
16 
17     if(ldepth == rdepth){
18         return (1<<ldepth) + countNodes(root->right);
19     }
20     else{
21         return (1<<rdepth) + countNodes(root->left);
22     }
23 }
24 
25 int getDepth(struct TreeNode* node) {
26     int depth = 0;
27 
28     while(node){
29         node = node->left;
30         depth++;
31     }
32 
33     return depth;
34 }

  对于,上面的代码一定要注意,对于(1<<ldepth)和(1<<rdepth)一定要注意加上括号,因为“+”比“<<”优先级高。

 

计算完全二叉树所有节点数

标签:

原文地址:http://www.cnblogs.com/geekliuyang/p/4646498.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!