[leetcode]222. Count Complete Tree Nodes

来源:互联网 发布:淘宝客进店买其他 编辑:程序博客网 时间:2024/06/04 23:23

题目链接:https://leetcode.com/problems/count-complete-tree-nodes/#/description

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.


class Solution {public:    int countNodes(TreeNode* root) {        if(!root) return 0;        int hl=0,hr=0;        TreeNode *l=root,*r=root;        while(l){hl++;l=l->left;}        while(r){hr++;r=r->right;}        if(hl==hr) return pow(2,hl)-1;        return 1+countNodes(root->left)+countNodes(root->right);    }};