1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
#include <iostream>
#include "stdlib.h"
#include "stdio.h"
using namespace std;
struct TreeNode {
int item; // The data in this node.
TreeNode *left; // Pointer to left subtree.
TreeNode *right; // Pointer to right subtree.
TreeNode(int str) {
item = str;
left = NULL;
right = NULL;
}
}; // end struct Treenode
void treeInsert(TreeNode *&root, int newItem) {
// Add the item to the binary sort tree to which the parameter
// "root" refers. Note that root is passed by reference since
// its value can change in the case where the tree is empty.
if ( root == NULL ) {
// The tree is empty. Set root to point to a new node containing
// the new item. This becomes the only node in the tree.
root = new TreeNode( newItem );
// NOTE: The left and right subtrees of root
// are automatically set to NULL by the constructor.
// This is important!
return;
}
else if ( newItem < root->item ) {
treeInsert( root->left, newItem );
}
else {
treeInsert( root->right, newItem );
}
} // end treeInsert()
void treeInsertLeft(TreeNode *&root, int parent, int child)
{
if ( root->item == parent ) {
root->left = new TreeNode(child);
return;}
if(root==NULL)return;
else{
treeInsertLeft( root->left, parent, child );
treeInsertLeft( root->right, parent, child );
}
}
void treeInsertRight(TreeNode *&root, int parent, int child)
{
if ( root->item == parent ) {
root->right = new TreeNode(child);
return;}
if(root==NULL)return;
else{
treeInsertRight( root->left, parent, child );
treeInsertRight( root->right, parent, child );
}
}
int main()
{
FILE* inFile;
FILE* outFile;
int aFirst;
int aSecond;
int tRoot;
char aString[1];
TreeNode *root; // Pointer to the root node in the tree.
root = NULL; // Start with an empty tree.
inFile = fopen("input.in", "r");
outFile = fopen("output.out", "w+");
fscanf(inFile, "%d", &tRoot);
treeInsert(root,tRoot);
treeInsertRight(root,tRoot,2);
treeInsertLeft(root,tRoot,3);
/*
treeInsertRight(root,3,4);
treeInsertLeft(root,3,9);
*/// <-- Crashes when trying to use these two
while(aString[0]!='F')
{fscanf(inFile, "%s", aString);
if(aString[0]=='L'||aString[0]=='R')
fscanf(inFile, "%d %d", &aFirst, &aSecond);
aFirst=aSecond=NULL;
}
fclose(inFile);
fclose(outFile);
return 0;
}
|