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

解法一:递归

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;
}

 

posted @ 2015-07-09 17:14  QingLiXueShi  阅读(448)  评论(0编辑  收藏  举报