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

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

 

    原文作者:QingLiXueShi
    原文地址: https://www.cnblogs.com/mengwang024/p/4633722.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞