222. Count Complete Tree Nodes
Medium
Given a complete binary tree, count the number of nodes.
Note:
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.
Example:
Input: 1 / \ 2 3 / \ / 4 5 6 Output: 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int countNodes(TreeNode* root) { if(!root) return 0; int lh=1, rh=1; TreeNode* ln = root->left; TreeNode* rn = root->right; while(ln) {++lh; ln = ln->left;} while(rn) {++rh; rn = rn->right;} if(lh==rh) return (1<<lh) - 1; return 1+countNodes(root->left)+countNodes(root->right); } }; |
No comments:
Post a Comment