I've recently started learning C++ and have a problem with understanding template mechanism. The task is first of all to build a user-defined binary tree. I can't compile my code.
#include <iostream>
using namespace std;
template <typename DataType> struct TreeNode
{
TreeNode(DataType val, TreeNode *leftPtr = null, TreeNode *rightPtr = null)
{
left = leftPtr;
right = rightPtr;
data = val;
}
TreeNode *left, *right;
DataType data;
};
template <typename DataType> TreeNode *BuildTree()
{
TreeNode *root = new TreeNode(10, new TreeNode(20), new TreeNode(30));
TreeNode *curRoot = root;
curRoot = curRoot->left;
curRoot->left = new TreeNode(40);
curRoot->left->left = new TreeNode(70);
curRoot->right = new TreeNode(50);
curRoot = curRoot->right;
curRoot->left = new TreeNode(80, new TreeNode(100), new TreeNode(110));
curRoot = root->right;
curRoot->left = new TreeNode(60);
curRoot = curRoot->left;
curRoot->right = new TreeNode(90, new TreeNode(120), new TreeNode(130));
return root;
}
int main()
{
TreeNode *treeRoot = BuildTree<int>();
cin.get();
return 0;
}
Function BuildTree
builds the concrete instance of tree, with concrete data type. Please help me to understand my mistake.
Please don't pay attention to the fact I don't free memory after using. That's just a draft.