You are on page 1of 3

struct Node{

int key;
Node* left;
Node* right;
};

struct BST{
Node *root;
};

Node* createNode(int key){


Node *node = new Node;
node->key = key;
node->left = node->right = NULL;
return node;
}

Node* createBST(){
BST* bst = new BST;
bst->root = NULL;
}

bool insertNode(Node* &root, int x){


if (root==NULL){
Node *node = createNode(x);
root=node;
return true;
}
if (root->key==x)
return false;
if (root->key>x)
return insertNode(root->left,x);
else
return insertNode(root->right,x);
}

Node* searchNode(Node* root, int x){


if (root==NULL)
return NULL;
if (root->key==x)
return root;
if (root->key>x)
return searchNode(root->left,x);
else
return searchNode(root->right,x);
}

void findSwap(Node* &root, Node* &p){


if (root->left!=NULL)
findSwap(root->left,p);
else{
p=root;
root=root->right;
}
}

bool deleteNode(Node* &root, int x){


if (root==NULL)
return false;
if (root->key<x)
return deleteNode(root->right,x);
if (root->key>x)
return deleteNode(root->left,x);
Node *p = root;
if (root->left==NULL)
root->left=root->right;
else if (root->right==NULL)
root->right=root->left;
else
findSwap(root->right,p);
delete p;
return true;
}

void levelPrint(Node* root){


queue<Node*> q;
q.push(root);
while (!q.empty()){
Node* node = q.front();
q.pop();
cout<<node->key<<' ';
if (!node->left)
q.push(node->left);
if (!node->right)
q.push(node->right);
}
}

void orderPrint(Node* root){


if (!root)
return;
//change these 3 lines' order
orderPrint(root->left);
cout<<root->key<<" ";
orderPrint(root->right);
}

int minValue(Node* node){


if (node == NULL)
return 1e9;

int leftMin = minValue(node->left);


int rightMin = minValue(node->right);

int value = 0;

if (leftMin < rightMin)


value = leftMin;
else
value = rightMin;

if (value < node->key)


return value;
else
return node->key;
}

int maxValue(Node* node){


if (node == NULL)
return -1e9;

int leftMax = maxValue(node->left);


int rightMax = maxValue(node->right);

int value = 0;
if (leftMax > rightMax)
value = leftMax;
else
value = rightMax;

if (value > node->key)


return value;
else
return node->key;
}

bool isValidBST(Node* node) {


if (node == NULL)
return true;

if (node->left != NULL
&& maxValue(node->left) >= node->key)
return false;
if (node->right != NULL
&& minValue(node->right) <= node->key)
return false;
if (!isValidBST(node->left) || !isValidBST(node->right))
return false;

return true;
}

You might also like