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

LeetCode Count Complete Tree Nodes

时间:2016-01-01 16:45:58      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

LeetCode Count Complete Tree Nodes

题目

技术分享

思路

这个树会灰常的大;
先沿着左右两遍计算深度。假设深度一样直接代公式算。
假设深度不一样。那就找最以下一层的断点。

代码

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

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