is this code OK?
Questions
1. Write a program to display the contents of a binary tree. Can you write a program that prints the nodes in a binary tree in sorted order? What about in reverse sorted order?
2. Write a program that counts the number of nodes in a binary tree.
4. Write a program that checks if the binary tree is properly sorted so that all nodes to the left of a given node are less than the value of that node, and all nodes to the right are greater than the value of that node.
#include <iostream>
#include <cstdlib>
using namespace std;
struct node
{
int val;
node* left;
node* right;
};
node* addnode(node* root, int key)
{
if (root == nullptr)
{
node* t = new node;
t->val = key;
t->left = t->right = nullptr;
return t;
}
else if (root->val < key)
root->right = addnode(root->right, key);
else
root->left = addnode(root->left, key);
return root;
}
void inorder_traverse(node* root)
{
if (root == nullptr) return;
inorder_traverse(root->left);
cout << root->val << '\n';
inorder_traverse(root->right);
}
void rev_inorder(node* root)
{
if (root == nullptr) return;
rev_inorder(root->right);
cout << root->val << '\n';
rev_inorder(root->left);
}
int count(node* root)
{
if (root == nullptr) return 0;
else return 1 + count(root->left) + count(root->right);
}
bool is_sorted(node* root)
{
if (root == nullptr) return true;
else if (root->left == nullptr && root->right == nullptr) return true;
else if (root->left == nullptr && root->right->val > root->val) return true;
else if (root->right == nullptr && root->left->val < root->val) return true;
else if (root->left->val < root->val && root->right->val > root->val) return true;
else return false;
if (is_sorted(root->left) && is_sorted(root->right)) return true;
}
int main()
{
srand(40);
node* root = nullptr;
for (int i = 5; i > 0; i--) root = addnode(root, rand()%10);
if (is_sorted(root)) cout << "Yes";
}