Problem:
Binary Search Tree II

Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I.

insert $k$: Insert a node containing $k$ as key into $T$.

find $k$: Report whether $T$ has a node containing $k$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

10
insert 30
insert 88
insert 12
insert 1
insert 20
find 12
insert 17
insert 25
find 16
print

Sample Output 1

yes
no
1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution in C (judge verdict: Runtime Error)

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

#define NIL -1
#define MAX 500000

struct node{
  int parent;
  int left;
  int right;
  int key;
};
typedef struct node Node;

void insert(int);
void inorder(int);
void preorder(int);
int find(int,int);

int  root=-1;
Node T[MAX];

int main(){
  int i, n, m;
  char str[10];

  scanf("%d",&n);

  for(i=0;i<n;i++) T[i].left=T[i].right=T[i].parent=-1;

  for (i=0;i<n;i++){
    scanf("%s",str);
    if(strcmp(str,"insert")==0){
      scanf("%d",&T[i].key);
      insert(i);
    }
    else if(strcmp(str,"print")==0){
      inorder(0);
      printf("\n");
      preorder(0);
      printf("\n");
    }
    else if(strcmp(str,"find")==0){
      scanf("%d",&m);
      if(find(root,m)!=-1) printf("yes\n");
      else printf("no\n");
    }
  }
  return 0;
}

void insert(int z){//printf("in\n" );
  int y = -1;
  int x = root;

  while(x != -1){
    y = x;
    if(T[z].key < T[x].key) x = T[x].left;
    else x = T[x].right;
  }

  T[z].parent = y;

  if(y == -1) root = z;

  else if(T[z].key < T[y].key) T[y].left = z;

  else T[y].right = z;
}

void inorder(int t){
  if(t != -1){
    inorder(T[t].left);
    printf(" %d",T[t].key);
    inorder(T[t].right);
  }
}

void preorder(int t){
  if(t != -1){
    printf(" %d",T[t].key);
    preorder(T[t].left);
    preorder(T[t].right);
  }
}

int find(int x, int k){
  if(x==-1 || k==T[x].key) return x;
  else if(k<T[x].key) return find(T[x].left,k);
  else return find(T[x].right,k);
}