Total Accepted: 22338 Total Submissions: 97234 Difficulty: Medium
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 2hnodes inclusive at the last level h.
/** * 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 treeDepth(TreeNode* root) { int dep=0; while(root){ dep++; root=root->left; } return dep; } int countNodes(TreeNode* root) { if(root==NULL){ return 0; } int ldep = treeDepth(root->left); int rdep = treeDepth(root->right); if(ldep>rdep){ return 1+countNodes(root->left) + ((1<<rdep)-1); } return 1+((1<<ldep)-1) + countNodes(root->right); } };
Next challenges: (E) Closest Binary Search Tree Value