← Home

222. Count Complete Tree Nodes

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
222

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 222. Count Complete Tree Nodes, the solution in this repository is mainly a two pointers solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

The notes already sitting in the source point us in the right direction:

  • time: O(N)

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are countNodes, height.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(log(N)^2)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 44 ms, faster than 63.40% of C++ online submissions for Count Complete Tree Nodes.
02//Memory Usage: 31 MB, less than 44.11% of C++ online submissions for Count Complete Tree Nodes.
03//time: O(N)
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 *     int val;
08 *     TreeNode *left;
09 *     TreeNode *right;
10 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
13 * };
14 */
15class Solution {
16public:
17    int countNodes(TreeNode* root) {
18        if(root == nullptr){
19            return 0;
20        }
21        
22        return 1 + countNodes(root->left) + countNodes(root->right);
23    }
24};
25
26//https://leetcode.com/problems/count-complete-tree-nodes/discuss/61958/Concise-Java-solutions-O(log(n)2)
27//Runtime: 56 ms, faster than 5.68% of C++ online submissions for Count Complete Tree Nodes.
28//Memory Usage: 30.9 MB, less than 67.20% of C++ online submissions for Count Complete Tree Nodes.
29//time: O(log(N)^2)
30/**
31 * Definition for a binary tree node.
32 * struct TreeNode {
33 *     int val;
34 *     TreeNode *left;
35 *     TreeNode *right;
36 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
37 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
38 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
39 * };
40 */
41class Solution {
42public:
43    int height(TreeNode* node){
44        //define a single tree node having height 0
45        //so an empty tree has height -1
46        return (node == nullptr) ? -1 : 1 + height(node->left);
47    };
48    
49    int countNodes(TreeNode* root) {
50        int h = height(root);
51        /*
52        if the height of root is negative,
53        that means it's an empty tree,
54        so there are 0 nodes
55        
56        o.w. check if right subtree's height is h-1,
57        if so, it means the last node appears in right subtree,
58        so left subtree is a complete binary tree with height = h-1.
59        left subtree has 2^h-1 nodes, plus 1 node for the root itself,
60        plus the right subtree's node count
61        
62        if right subtree's height is not h-1(then it's h-2),
63        then the last node appears in left subtree,
64        so right subtree is a complete binary tree with height = h-2.
65        right subtree has 2^(h-1)-1 nodes, plus 1 node for the root itself,
66        plus the left subtree's node count
67        */
68        return (h < 0) ? 0 : 
69            (height(root->right) == h-1) ? (1 << h) + countNodes(root->right) : (1 << h-1) + countNodes(root->left);
70    }
71};
72
73//iterative version
74//https://leetcode.com/problems/count-complete-tree-nodes/discuss/61958/Concise-Java-solutions-O(log(n)2)
75//Runtime: 48 ms, faster than 34.76% of C++ online submissions for Count Complete Tree Nodes.
76//Memory Usage: 30.9 MB, less than 73.37% of C++ online submissions for Count Complete Tree Nodes.
77/**
78 * Definition for a binary tree node.
79 * struct TreeNode {
80 *     int val;
81 *     TreeNode *left;
82 *     TreeNode *right;
83 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
84 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
85 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
86 * };
87 */
88class Solution {
89public:
90    int height(TreeNode* node){
91        return (node == nullptr) ? -1 : 1 + height(node->left);
92    };
93    
94    int countNodes(TreeNode* root) {
95        int count = 0, h = height(root);
96        
97        while(root != nullptr){
98            if(height(root->right) == h-1){
99                //add left subtree and root's count
100                count += (1<<h);
101                root = root->right;
102            }else{
103                //add right subtree and root's count
104                count += (1<<h-1);
105                root = root->left;
106            }
107            /*
108            in next iteration,
109            we look into the incomplete left or right subtree,
110            and it's height is current height -1
111            */
112            --h;
113        }
114        
115        return count;
116    }
117};

Cost

Complexity

Time
O(log(N)^2)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.