0

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";
}
Daniel
  • 11
  • 1
    If you don't have any specific issues with your code [Codereview](https://codereview.stackexchange.com/) might a better place to ask this :) As a first impression: You tagged it C++, but most of it is C. And `using namespace std;` [is considered bad practice](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Lukas-T Dec 20 '19 at 08:55
  • The question doesn't show any research effort. – User_67128 Dec 20 '19 at 13:01

0 Answers0