I'm getting error C2109: subscript requires array or pointer type
// CPP btree.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
class TreeNode
{
public:
TreeNode(string str): data(str), left(NULL), right(NULL) {} // Constructor. Make a node containing str.
string data; // The data in this node.
TreeNode *left; // Pointer to left subtree.
TreeNode *right; // Pointer to right subtree.
};
typedef TreeNode* TreeNodePtr;
void treeInsert(TreeNodePtr& root, string newItem)
{
if ( root == NULL ) {
root = new TreeNode( newItem );
return;
}
else if ( newItem < root->data ) {
treeInsert( root->left, newItem );
}
else
{
treeInsert( root->right, newItem );
}
} // end treeInsert()
void traverseinorder(TreeNode *root ) // a recursive function to print the nodes values based on an inorder traversal
{
if ( root != NULL ) {
traverseinorder( root->left );
cout << root->data << " ";
traverseinorder( root->right );
}
} // end traverseinorder()
int size( TreeNode *root ) // the number of nodes in the tree
{
if ( root == NULL )
return 0; // The tree is empty. It contains no nodes.
else
{
int count = 1; // Start by counting the root.
count += size(root->left); // Add the number of nodes in the left subtree.
count += size(root->right); // Add the number of nodes in the right subtree.
return count;
}
} // end size()
bool isleaf(TreeNode *root) //returns true if the node is a leaf
{
return (root->left==NULL && root->right==NULL);
}
int parent(int pos) // returns the index of the parent
{
return (pos - 1) / 2;
}
int leftchild(int pos) // returns the index of the left child
{
return (pos * 2) + 1;
}
int rightchild(int pos) // returns the index of the right child
{
return (pos * 2) + 2;
}
int height(TreeNode *root) // returns the height of the tree
{
if (root==NULL)
{
return(0);
}
else
{
// compute the depth of each subtree
int lheight = height(root->left);
int rheight = height(root->right);
// use the larger one
if (lheight > rheight) return(lheight+1);
else return(rheight+1);
}
}
int main(int argc, char* argv[])
{
treeInsert[0]=5;
treeInsert[1]=10;
treeInsert[2]=2;
treeInsert[3]=5;
treeInsert[4]=7;
treeInsert[5]=12;
treeInsert[6]=3;
treeInsert[7]=9;
treeInsert[8]=8;
cout << leftchild(3);
cout << height();
cout << isleaf(7);
cout << isleaf(2);
cout << parent(5);
traverseinorder();
}