Enter n, then n trees, to create a two-fork lookup tree. Output the left and right subtree of each node from small to large, empty output #
#include <cstdio> #include <iostream>using namespace std;typedef struct node{int data; struct node *lchild,*rchild;} Node;void input (NODE *root,int value) {if (value==root->data) {return; } else if (Value>root->data) {if (root->rchild==null) {root->rchild=new NODE; root->rchild->data=value; root->rchild->lchild=null; root->rchild->rchild=null; } else{input (Root->rchild,value); }} else{if (root->lchild==null) {root->lchild=new NODE; root->lchild->data=value; root->lchild->lchild=null; root->lchild->rchild=null; } else{input (Root->lchild,value); }}}int count=0,n;void Preorder (NODE *root) {if (root==null) return; Preorder (Root->lchild); if (count<n) {printf ("%d (", root->data); if (root->lchild==null) {printf ("#"); } else{printf ("%d", root->lchild->data); } if (Root->rchild==null) {printf (", #) \ n"); } else{printf (",%d) \ n", root->rchild->data); } count++; } preorder (Root->rchild);} int main () {node *root=new node; root->lchild=root->rchild=null; int A; scanf ("%d", &n); for (int i=0;i<n;i++) {scanf ("%d", &a); Input (root,a); } preorder (root); return 0;}
Q114 First binary search tree (chained)