leetcode_222
Given a complete binary tree, count the number of nodes.
Note:
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6Solutions
/**
* 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) return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
};Last updated