标签:
这个树会灰常的大;
先沿着左右两遍计算深度。假设深度一样直接代公式算。
假设深度不一样。那就找最以下一层的断点。
int maxD, num;
int calDeepFromRight(struct TreeNode* root) {
int ans = 0;
while (root) {
ans++;
root = root->right;
}
return ans;
}
int calDeepFromLeft(struct TreeNode* root) {
int ans = 0;
while (root) {
ans++;
root = root->left;
}
return ans;
}
void findBreakPoint(struct TreeNode* root, int pos, int deep) {
if (num != -1) return;
if (root == NULL && deep == maxD) {
num = 1;
int base = 1;
for (int i = 1; i < deep - 1; i++) num += (base *= 2);
num += pos;
return;
}
else {
if (root == NULL) return;
findBreakPoint(root->left, pos * 2, deep + 1);
findBreakPoint(root->right, pos * 2 + 1, deep + 1);
}
}
int countNodes(struct TreeNode* root) {
int ld = calDeepFromLeft(root), rd = calDeepFromRight(root);
maxD = ld;
if (ld == rd) {
if (ld == 0) return 0;
int base = 1;
num = 1;
for (int i = 1; i < ld; i++) num += (base *= 2);
}
else {
num = -1;
findBreakPoint(root, 0, 1);
}
return num;
}
LeetCode Count Complete Tree Nodes
标签:
原文地址:http://www.cnblogs.com/mengfanrong/p/5093316.html