-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path134CountCompleteTreeNodes.cpp
More file actions
60 lines (47 loc) · 1.11 KB
/
Copy path134CountCompleteTreeNodes.cpp
File metadata and controls
60 lines (47 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
int main() {
/*
1
/ \
2 3
/ \ /
4 5 6
*/
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
Solution obj;
cout << obj.countNodes(root) << endl; // Output: 6
return 0;
}
/*
if(root == NULL) return 0;
queue<TreeNode*> q;
q.push(root);
int count = 0;
while(!q.empty()){
TreeNode* node = q.front();
q.pop();
count++;
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
return count;
*/