222. Count Complete Tree Nodes
Given a complete binary tree, count the number of nodes.
Note:
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.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
题目链接:https://leetcode-cn.com/problems/count-complete-tree-nodes/
思路
法一:递归
常规思路和计算二叉树深度一样,不断向下递归,返回左子树节点数+右子树节点数+1。
时间复杂度O(n)。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
return countNodes(root->left) + countNodes(root->right) + 1;
}
};
法二:二分搜索
由于本题特殊地指定二叉树为完全树,因此只要知道树的深度,对最后一层节点进行二分搜索验证是否存在即可。
这里需要用到二叉树中的数字关系:
1)深度=d时,一层的节点数量在 0~ 之间;最后一层满时,树的节点数为 。
2)用层序遍历的方法从1开始标记节点索引,父节点为n时,子节点为 和 ;相反,子为n时,父为 。
深度计算只需要向单一左子树向下探索即可。
时间复杂度降到
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
int dep = getDepth(root);
if (dep==1) return 1;
int l = pow(2,dep-1), r = pow(2,dep);
while(l<r){
int mid = (l+r)/2;
if(exist(mid, root)) l = mid+1;
else r = mid;
}
return l-1;
}
int getDepth(TreeNode* root){
if(!root) return 0;
return getDepth(root->left)+1;
}
bool exist(int mid, TreeNode* root){
if(mid<=1) return NULL;
stack<int> s;
while(mid>1){
s.push(mid%2);
mid /= 2;
}
while(s.size()>1){
if(s.top()==0) root = root->left;
else root = root->right;
s.pop();
}
if(s.top()==0) return root->left!=NULL;
else return root->right!=NULL;
}
};
ps.二分查找指针变化和终止条件判定不太熟练。