美文网首页
Count Complete Tree Nodes解题报告

Count Complete Tree Nodes解题报告

作者: 黑山老水 | 来源:发表于2017-09-29 02:49 被阅读62次

    Description:

    Given a complete binary tree, count the number of nodes.

    Link:

    https://leetcode.com/problems/count-complete-tree-nodes/description/

    解题方法:

    1. 给定当前的节点,分别去算这个节点最左边的level和最右边的level。
    2. 如果这两个level相等,那么这个节点可以看作为一个满二叉树的根节点,因为我们求出了这个满二叉树的level,自然可以算出这个满二叉树的节点总数。
    3. 如果这两个level不相等,那么我们把这个节点看做一个单独的节点,并且对这个节点的左右子节点重复过程1到2或者1到3。

    Time Complexity:

    O(logN)

    完整代码:

    int countNodes(TreeNode* root) 
        {
            if(!root)
                return 0;
            int ll = 0, rl = 0;
            TreeNode* l = root; TreeNode* r = root;
            while(l) {ll++; l = l->left;}
            while(r) {rl++; r = r->right;}
            if(ll == rl) return pow(2, ll) - 1; //if this is a full binary tree
            return 1 + countNodes(root->left) + countNodes(root->right);  //or treat this node as single node
        }
    

    相关文章

      网友评论

          本文标题:Count Complete Tree Nodes解题报告

          本文链接:https://www.haomeiwen.com/subject/kuebextx.html