forked from keyanyang/cs-fundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcourse2_week2_challenge.cpp
73 lines (59 loc) · 1.9 KB
/
course2_week2_challenge.cpp
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
61
62
63
64
65
66
67
68
69
70
71
72
73
// Your job is to implement the function "int count(Node *n)" that computes and returns the number of nodes in the binary tree that has n as its root.
// When you write your code below, assume that a class type called "Node" has already been defined for you; you cannot change the class definition.
// This class type has two child pointers ("left" , "right"). There is also a constructor Node() that initializes the children to nullptr and a
// destructor that deallocates the subtree's memory recursively.
/********************************************************
You may assume that the following Node class has already
been defined for you previously:
class Node {
public:
Node *left, *right;
Node() { left = right = nullptr; }
~Node() {
delete left;
left = nullptr;
delete right;
right = nullptr;
}
};
You may also assume that iostream has already been included.
Implement the function "int count(Node *n)" below to return
an integer representing the number of nodes in the subtree
of Node n (including Node n itself).
*********************************************************/
#include <queue>
using namespace std;
int count(Node *n) {
// Implement count() here.
unsigned cnt = 0;
queue <Node*> q;
q.push(n);
while (!q.empty()) {
Node* cur = q.front();
cnt += 1;
if (cur->left != nullptr) {
q.push(cur->left);
}
if (cur->right != nullptr) {
q.push(cur->right);
}
q.pop();
}
return cnt;
}
int main() {
Node *n = new Node();
n->left = new Node();
n->right = new Node();
n->right->left = new Node();
n->right->right = new Node();
n->right->right->right = new Node();
// This should print a count of six nodes
std::cout << count(n) << std::endl;
// Deleting n is sufficient to delete the entire tree
// because this will trigger the recursively-defined
// destructor of the Node class.
delete n;
n = nullptr;
return 0;
}