zoukankan      html  css  js  c++  java
  • 【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;
    }
  • 相关阅读:
    [SDOI2011]消防
    10.15 上午 考试
    松鼠搬家 ( 切比雪夫距离 到 曼哈顿距离 )
    10.14 上午 考试
    10.13 下午
    bzoj2640 元素 线性基+贪心
    猪国杀 大模拟
    10.13 上午 考试
    10.12 两次考试
    阿狸和桃子的游戏
  • 原文地址:https://www.cnblogs.com/mengwang024/p/4633722.html
Copyright © 2011-2022 走看看