Question

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.

Difficulty:Medium

Category:Tree, Binary-Search

Analyze

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
//Runtime: 16ms
class Solution {
 public:
  int countNodes(TreeNode* root) {
    if (!root) return 0;
    if (!root->left && !root->right) return 1;

    int l = countNodes(root->left);
    int r = countNodes(root->right);
    return l + r + 1;
  }
};
By guozetang            Updated: 2020-09-19 13:02:30

results matching ""

    No results matching ""