#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

struct tnode {
   char ch;
   struct tnode *left;
   struct tnode *right;
};
void          addtree(struct tnode *, char );
struct tnode *newnode(char );
void          treeprint(struct tnode *);
struct tnode *lookup (struct tnode *, char );
struct tnode *lookup2(struct tnode *, char );

void main(void)
{
   struct tnode *root;
   struct tnode *p;
   char c;
   root = NULL;
   while ((c = getchar()) != '\n') {
      if (root == NULL) root = newnode(c);
      else addtree(root, c);
   }
   treeprint(root);
   printf("\n");
   p = lookup(root, 'x');
   if (p == NULL) printf("Not found\n");
   else printf("Here it is: %c\n", p -> ch);
   p = lookup2(root, 'x');
   if (p == NULL) printf("Not found\n");
   else printf("Here it is: %c\n", p -> ch);
}

/* addtree: add a node, non-recursive */
void addtree(struct tnode *p, char c)
{
   for (;;) {
      if ((p -> ch) == c) return; /* ignore */
      else if ((p -> ch) > c) { /* go left */
         if ((p -> left) == NULL) {
            p -> left = newnode(c);
	    return;
         }
         else p = p -> left;
      }
      else if ((p -> ch) < c) { /* go right */
         if ((p -> right) == NULL) {
            p -> right = newnode(c);
	    return;
         }
         else p = p -> right;
      }
   }
}

/* lookup: find the node of a char c (recursive version) */
struct tnode *lookup(struct tnode *p, char c)
{
   if (p == NULL) return NULL;
   if ((p -> ch) == c) return p;
   if ((p -> ch) > c) /* go left */
       p = lookup(p -> left, c);
   else /* if ((p -> ch) < c) */
       p = lookup(p -> right, c);
   return p;
}

/* lookup: find the node of a char c (improved version) */
struct tnode *lookup2(struct tnode *p, char c)
{
   for (;;) {
      if (p == NULL) return NULL;
      if ((p -> ch) == c) return p;
      if ((p -> ch) > c)  /* go left */
         p = p -> left;
      else  /* if ((p -> ch) < c)   go right */
         p = p -> right;
   }
}

/* newnode: fix up a new node */
struct tnode *newnode(char c)
{
   struct tnode *p = (struct tnode *)
        malloc(sizeof(struct tnode));
   p -> ch = c;
   p -> left = p -> right = NULL;
   return p;
}

/* treeprint: recursive inorder print of tree p */
void treeprint(struct tnode *p)
{
   if (p != NULL) {
      treeprint(p -> left);
      printf("%c", p -> ch);
      treeprint(p -> right);
   }
}


