// TreeNode: simple node in a binary search tree
public class TreeNode {
public char data; // data at each node
public TreeNode left, right;
public TreeNode(char ch) { // const. leaf node
data = ch;
left = right = null;
}
}
// Tree: binary search tree of chars
public class Tree {
private TreeNode root; // hidden root node
public Tree() {
root = null;
}
// insert: if new entry, insert in tree
public void insert(char ch) {
if (root == null) { // handle empty tree
root = new TreeNode(ch);
return;
}
TreeNode p = root; // search down from root
while (true) {
if (p.data > ch) { // left
if (p.left == null) {
p.left = new TreeNode(ch);
return;
}
else p = p.left;
}
else if (p.data < ch) { // right
if (p.right == null) {
p.right = new TreeNode(ch);
return;
}
else p = p.right;
}
else return; // found! Don't insert
}
}
// inorderTraversal: because root is hidden
public void inorderTraversal() {
inorderT(root);
}
// inorderT: recursive function, does the work
private void inorderT(TreeNode p) {
if (p != null) {
inorderT(p.left);
System.out.print(p.data);
inorderT(p.right);
}
}
}
// TreeTest: test binary search tree
import java.io.*;
public class TreeTest {
public static void main(String[] argv)
throws IOException {
Tree tree = new Tree();
int ch;
while ((ch =(char)System.in.read())!='\n'){
tree.insert((char)ch);
}
tree.inorderTraversal();
System.out.println();
}
} |
/* tree.h: header file for tree.c */
void insert(char );
void inordertraversal(void);
/* tree.c: create binary tree */
#include <stdio.h>
#include <stdlib.h> /* for malloc */
#include "tree.h"
struct tnode {
char data;
struct tnode *left;
struct tnode *right;
};
/* newnode: fix up a new node */
static struct tnode *newnode(char ch) {
struct tnode *p = (struct tnode *)
malloc(sizeof(struct tnode));
p -> data = ch;
p -> left = p -> right = NULL;
return p;
}
static void inordert(struct tnode *);
struct tnode *root = NULL;
/* insert: add a node, non-recursive */
void insert(char ch) {
struct tnode *p;
if (root == NULL) { /* empty tree */
root = newnode(ch);
return;
}
p = root;
for (;;) {
if ((p -> data) > ch) { /* left */
if ((p -> left) == NULL) {
p -> left = newnode(ch);
return;
}
else p = p -> left;
}
else if ((p -> data) < ch) {/* right */
if ((p -> right) == NULL) {
p -> right = newnode(ch);
return;
}
else p = p -> right;
}
else return; // found! Don't insert
}
}
/* inordertraversal: because root is hidden */
void inordertraversal(void) {
inordert(root);
}
/* inordert: recursive inorder print */
static void inordert(struct tnode *p) {
if (p != NULL) {
inordert(p -> left);
printf("%c", p -> data);
inordert(p -> right);
}
}
/* treetest.c: test tree.c */
#include <stdio.h>
#include "tree.h"
int main() {
char c;
while ((c = getchar()) != '\n') {
insert(c);
}
inordertraversal();
printf("\n");
}
|