[LeetCode] Count Complete Tree Nodes


Count Complete Tree Nodes

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

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.

對於完全二叉樹,去掉最后一層,就是一棵滿二叉樹,我們知道高度為 h 的滿二叉樹結點的個數為 2^h - 1 個,所以要知道一棵完全二叉樹的結點個數,只需知道最后一層有多少個結點。而完全二叉樹最后一層結點是從左至右連續的,所以我們可以依次給它們編一個號,然后二分搜索最后一個葉子結點。我是這樣編號的,假設最后一層在 h 層,那么一共有 2^(h-1) 個結點,一共需要 h - 1 位來編號,從根結點出發,向左子樹走編號為 0, 向右子樹走編號為 1,那么最后一層的編號正好從0 ~ 2^(h-1) - 1。復雜度為 O(h*log(2^(h-1))) = O(h^2)。下面是AC代碼。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isOK(TreeNode *root, int h, int v) {
13         TreeNode *p = root;
14         for (int i = h - 2; i >= 0; --i) {
15             if (v & (1 << i)) p = p->right;
16             else p = p->left;
17         }
18         return p != NULL;
19     }
20     
21     int countNodes(TreeNode* root) {
22         if (root == NULL) return 0;
23         TreeNode *p = root;
24         int h = 0;
25         while (p != NULL) {
26             p = p->left;
27             ++h;
28         }
29         int l = 0, r = (1 << (h - 1)) - 1, m;
30         while (l <= r) {
31             m = l + ((r - l) >> 1);
32             if (isOK(root, h, m)) l = m + 1;
33             else r = m - 1;
34         }
35         return (1 << (h - 1)) + r;
36     }
37 };

 

或者可以用遞歸的方法,對於這個問題,如果從某節點一直向左的高度 = 一直向右的高度, 那么以該節點為root的子樹一定是complete binary tree. 而 complete binary tree的節點數,可以用公式算出 2^h - 1. 如果高度不相等, 則遞歸調用 return countNode(left) + countNode(right) + 1.  復雜度為O(h^2)。

該方法參考:http://blog.csdn.net/xudli/article/details/46385011

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int getHeight(TreeNode *root, bool tag) {
13         int h = 0;
14         while (root != NULL) {
15             if (tag) root = root->left;
16             else root = root->right;
17             ++h;
18         }
19         return h;
20     }
21     
22     int countNodes(TreeNode* root) {
23         if (root == NULL) return 0;
24         int left = getHeight(root, true);
25         int right = getHeight(root, false);
26         if (left == right) return (1 << left) - 1;
27         else return countNodes(root->left) + countNodes(root->right) + 1;
28     }
29 };

 


免責聲明!

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



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