3.5.2
统计有两个儿子节点的节点个数
#include <cstdio>
#include <iostream>
#include <stack>
using namespace std;
template<typename T>
struct node{
node<T> * l;
node<T> * r;
T data;
node(){
l = nullptr, r = nullptr;
}
node(const T d){
data = d;
l = nullptr, r = nullptr;
}
node & operator= (const node & n){
data = n.data;
l = n.l, r = n.r;
}
};
template<typename T>
class bt{
private:
node<T> * root;
int size;
void insert(node<T> * n, const T & data){
if (data == n->data) return;
if (data < n->data){
if (n->l != nullptr){
insert(n->l, data);
}
else{
n->l = new node<T>(data);
return;
}
}
else{
if (n->r != nullptr){
insert(n->r, data);
}
else{
n->r = new node<T>(data);
return;
}
}
}
void print(ostream & os, node<T> * n, int depth){
for (int i = 0; i < depth << 2; ++i) os << ' ';
os << n->data << endl;
if (n->l != nullptr) print(os, n->l, depth + 1);
if (n->r != nullptr) print(os, n->r, depth + 1);
}
int count(node<T> * n){
int ans = 0;
if (n->l && n->r){
++ans;
}
if (n->l) ans += count(n->l);
if (n->r) ans += count(n->r);
return ans;
}
public:
bt(){
root = nullptr;
size = 0;
}
friend ostream & operator<< (ostream & os, bt<T> & t){
if (!t.size) return os;
t.print(os, t.root, 0);
return os;
}
void insert(T data){
++size;
if (root == nullptr) root = new node<T>(data);
else insert(root, data);
}
int count(){
return count(root);
}
};
typedef unsigned long long ull;
ull k1, k2, mod;
ull xorshift128add(){
ull k3 = k1, k4 = k2;
k1 = k4;
k3 = k3 << 17 ^ k3;
k2 = k3 >> 23 + k4 << 10;
return k2 + k4;
}
int main(){
bt<int> t;
ios::sync_with_stdio(false);
int T;
cin >> T;
cin >> k1 >> k2 >> mod;
cout << t << endl;
for (int i = 0; i < T; ++i){
int temp = (int)(xorshift128add() % mod);
cout << "inserting " << temp << endl;
t.insert(temp);
}
cout << t << endl;
cout << t.count() << endl;
return 0;
}
/*
20
123456789 987654321 23
(19)
/----/ \----\
(15) 21
/-/ \-\ \
(12) 18 22
/ \ /
9 14 17
/ / /
(6) 13 16
/ \
5 7
*/