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

【LeetCode 222_完全二叉树_遍历】Count Complete Tree Nodes

时间:2015-07-09 17:55:25      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

解法一:递归

int countNodes(TreeNode* root)
{
    if (root == NULL)
        return 0;
    
    TreeNode *pLeft = root->left;
    TreeNode *pRight = root->right;
    int ldepth = 0, rdepth = 0;
    while (pLeft) {
        ldepth++;
        pLeft = pLeft->left;
    }
    while (pRight) {
        rdepth++;
        pRight = pRight->right;
    }
    if (ldepth == rdepth) 
        return (1 << (ldepth + 1)) - 1;
    else
        return countNodes(root->left) + countNodes(root->right) + 1;
}

解法二:迭代

int GetDepth(TreeNode *root)
{
    int depth = 0;
    while (root) {
        depth++;
        root = root->left;
    }
    return depth;
}

int countNodes(TreeNode* root)
{
    if (root == NULL)
        return 0;

    int depth = GetDepth(root);
    int leaf = 0;
    int depth_left, depth_right;
    while (true) {
        depth_left = GetDepth(root->left);
        depth_right = GetDepth(root->right);
        if (depth_left == 0 && depth_right == 0) {
            leaf += 1;
            break;
        }
            
        if (depth_left == depth_right) {
            leaf += 1 << (depth_left - 1);
            root = root->right;
        } else {
            root = root->left;
        }
    }
    return (1 << (depth - 1)) - 1 + leaf;
}

 

【LeetCode 222_完全二叉树_遍历】Count Complete Tree Nodes

标签:

原文地址:http://www.cnblogs.com/mengwang024/p/4633722.html

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