Skip to content

Instantly share code, notes, and snippets.

Created June 16, 2014 11:31
Show Gist options
  • Save anonymous/4abc45267995c61551cc to your computer and use it in GitHub Desktop.
Save anonymous/4abc45267995c61551cc to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define max(a, b) (a > b ? a : b)
typedef struct _node {
struct _node * left, * right;
int value;
} node;
node * createNode(int x) {
node * newNode = new node;
if (node == NULL)
return NULL;
newNode->left = newNode->right = NULL;
newNode->value = x;
return newNode;
}
void addNode(node * root, node * newNode) {
if (root == null) {
root = newNode;
return;
}
if (root->value > newNode->value)
return addNode(root->left, newNode);
else if (root->value < newNode->value)
return addNode(root->right, newNode);
else
return;
}
void addNode(node * root, int x) {
return addNode(root, createNode(x));
}
void printTree(node * root) {
if (root != NULL) {
printTree(root->left);
printf("%5d", root->value);
printTree(root->right);
}
return;
}
// Dem nut co dung 2 con
int counterNodeHave2Child(node * root) {
if (root == NULL)
return 0;
return ((root->left != NULL && root->right != NULL) ? 1 : 0) +
nodeHave2Child(root->left) + nodeHave2Child(root->right);
}
// Dem nut co dung 1 con
int counterNodeHave1Child(node * root) {
if (root == NULL)
return 0;
return ((root->left != NULL && root->right == NULL) || (root->left == NULL && root->right != NULL) ? 1 : 0) +
nodeHave2Child(root->left) + nodeHave2Child(root->right);
}
// So Hoan Thien (co' so^' luong. uoc so bang chinh no)
bool isPerfectNumber(int x) {
s = 0;
for (int i = 1; i < x; i++) {
if (x % i == 0) s++;
}
if (s == x) return true;
return false;
}
// Dem node la so hoan thien
int counterNodePerfectNumber(node * root) {
if (root == NULL)
return 0;
return (isPerfectNumber(root->value) ? 1 : 0) +
counterNodePerfectNumber(root->left) + counterNodePerfectNumber(root->right);
}
// Xuat cac node o ta^`ng k
void printNodeAtLevel(node * root, int k) {
if (root != NULL) {
printNodeAtLevel(root->left, k - 1);
if (k == 0) printf("%5f", root->value);
printNodeAtLevel(root->right, k - 1);
}
}
// Tim chieu cao cua cay
int getTreeHeight(node * root) {
if (root == NULL) return 0;
return 1 + max(getTreeHeight(root->left), getTreeHeight(root->right));
}
// Dem nut la so chan
int counterNodeEven(node * root) {
if (root == NULL)
return 0;
return ((root->value % 2 == 0) ? 1 : 0) +
counterNodeEven(root->left) + counterNodeEven(root->right);
}
// Dem nut la && nut cha~n
int counterNodeLeafEven(node * root) {
if (root == NULL)
return 0;
return ((root->left == NULL && root->right == NULL && root->value % 2 == 0) ? 1 : 0) +
counterNodeLeafEven(root->left) + counterNodeLeafEven(root->right);
}
int main() {
node * root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment