You are on page 1of 2

// BÀI TẬP 2 CÂY NHỊ PHÂN

#include<iostream>
using namespace std;
struct Node
{
int key;
Node* left;
Node* right;
};
void Init(Node*& root)
{
root = NULL;
}
Node* createNode(int x)
{
Node* p = new Node;
p->key = x;
p->right = NULL;
p->left = NULL;
return p;
}
void addNode(Node*& root, int x)
{
Node* p = root;
if (root == NULL)
{
root = createNode(x);
}
else
{
Node* r = NULL;
while ( p!= NULL && p->key != x)
{
r = p;
if (p->key > x)
{
p = p->left;
}
else
{
p = p->right;
}
}
if ( p== NULL )
{
p = createNode(x);
if (r->key > p->key)
{
r->left = p;
}
else
{
r->right = p;
}
}
}
}
//duyệt rồi tính tổng các số /5
int sumfive(Node*& root, int &sum)
{
if (root != 0)
{
sumfive(root->left, sum);
if (root->key % 5 == 0)
{
sum = sum + root->key;
}
sumfive(root->right, sum);
}
return sum;
}
//đếm nút lá có giá trị lẽ
int countodd(Node*& root, int& count)
{
if (root != 0)
{
countodd(root->left, count);
if (root->key % 2 != 0 && root->left==NULL && root-
>right==NULL)
{
count++;
}
countodd(root->right, count);
}
return count;
}
void lnr(Node*& root)
{
if (root != 0)
{
lnr(root->left);
cout << root->key << " ";
lnr(root->right);
}
}
int main()
{
Node* root;
Init(root);
int sum = 0, count =0;
addNode(root, 10);
addNode(root, 6);
addNode(root, 18);
addNode(root, 14);
addNode(root, 23);
addNode(root, 12);
addNode(root, 15);
addNode(root, 3);
addNode(root, 8);
addNode(root, 5);
addNode(root, 4);
addNode(root, 9);
lnr(root);
cout<<endl<<"TONG CAC BOI CHIA HET CHO NAM "<<sumfive(root, sum);
cout << endl << "SO NOT LA LE LA " << countodd(root, count);
return 0

You might also like