【LeetCode】222. Count Complete Tree Nodes
Count Complete Tree Nodes
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.
完全二叉树相比普通二叉树,在计数时候一个trick在于,当最后一层是满的(最左深度等于最右深度),
就不需要通过遍历方式来计数,直接等于2^h - 1
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int countNodes(TreeNode* root) { if(root == NULL) return 0; TreeNode* l = root; int lefth = 0; while(l->left) { lefth ++; l = l->left; } TreeNode* r = root; int righth = 0; while(r->right) { righth ++; r = r->right; } if(lefth == righth) return pow(2.0, lefth+1) - 1; else return 1 + countNodes(root->left) + countNodes(root->right); } };