222. Count Complete Tree Nodes

来源:互联网 发布:linux修改用户组 编辑:程序博客网 时间:2024/05/16 03:37

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

Definition of a complete binary tree from Wikipedia:

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.


1.我的答案,层次遍历(超时)

int countNodes(TreeNode* root) {        if(root == NULL)        return 0;        queue<TreeNode*>q;        q.push(root);        int count = 0;        while(!q.empty()){            TreeNode* t = q.front();            count++;            q.pop();            if(t->left)                q.push(t->left);            if(t->right)                q.push(t->right);        }        return count;    }

2.递归 168ms

int countNodes(TreeNode* root) {        if(root == NULL)        return 0;        int ll = 0, lr = 0;        TreeNode* tl = root, *tr = root;        while(tl){            ll++;            tl = tl->left;        }        while(tr){            tr = tr->right;            lr++;        }        if(ll == lr)        return (1<<ll)-1;        else        return 1+countNodes(root->left)+countNodes(root->right);            }


0 0