計算完全二叉樹所有節點數


  今天在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)一定要注意加上括號,因為“+”比“<<”優先級高。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM