我编写了一个代码来创建和显示二叉树。该程序有效并满足了我所学课程的要求,但是之后我尝试添加到工作程序中以找到树的高度,但到目前为止没有运气。我查看了许多示例,但我对程序所做的任何添加或更改都没有使它起作用。
#include <cstdlib>
#include <iostream>
#include <cstdio>
using namespace std;
class TreeNode
{ public:
TreeNode *pLeft;
int data;
TreeNode *pRight;
TreeNode *leftHeight;
TreeNode *rightHeight;
TreeNode(int num)
{
data = num;
pLeft = NULL;
pRight = NULL;
}
}; ////////////////////////////////////////////
class Binary_Tree
{ private:
//int getHeight;
public:
TreeNode *rootPtr;
Binary_Tree()
{ rootPtr = NULL;
}
/* ---------------------------------- */
void Insert(int value)
{
TreeNode *pNewNode = new TreeNode(value);
TreeNode *pCurrent;
TreeNode *pPrevious;
pPrevious = NULL;
pCurrent = rootPtr;
while(pCurrent != NULL)
{ pPrevious = pCurrent;
if (value < (pPrevious -> data))
pCurrent = pCurrent -> pLeft;
else
pCurrent = pCurrent -> pRight;
}
if(pPrevious == NULL)
{ rootPtr = pNewNode;
}
else
{ if (value < (pPrevious -> data))
{ pPrevious -> pLeft = pNewNode;
pNewNode -> pLeft = pCurrent;
}
else
{ pPrevious -> pRight = pNewNode;
pNewNode -> pRight = pCurrent;
}
}
}
/* ------------------------------------------- */
int getHeight(TreeNode *TreePtr)
{
if( TreePtr == NULL)
{
return(0);
}
else
{
leftHeight = getHeight(r->pLeft);
rightHeight = getHeight(r->pRight);
if(leftHeight > rightHeight)
{
return(leftHeight + 1);
}
else
{
return(rightHeight + 1);
}
}
}
/* ------------------------------------------- */
void Display(TreeNode *TreePtr, int count)
{
if(TreePtr !=NULL)
{
count++;
Display(TreePtr -> pRight, count);
for(int i = i; i < count; i++)
{
printf(" ");
}
printf("%d \n", TreePtr -> data);
Display(TreePtr -> pLeft, count);
}
}//////////////////////end display //////////////////////
void DisplayInOrder(TreeNode *TreePtr)
{
if(TreePtr != NULL)
{
DisplayInOrder(TreePtr -> pLeft);
cout << TreePtr -> data << endl;
DisplayInOrder(TreePtr -> pRight);
}
}
};
/* -------------------------------------- */
/////////////////////////////////////////////////////////////
int main()
{ int number[8] = {7, 9, 3, 2, 12, 5, 8};
Binary_Tree Tree;
for (int i = 0; i <8; i++)
{
cout << "data inserted = "<< number[i] << endl;
Tree.Insert(number[i]);
}
cout << endl << "Display Tree" << endl << endl;
Tree.Display(Tree.rootPtr, 0);
cout << endl;
cout << endl << "tree height" << endl << endl;
getHeight(root);
cout << endl;
Tree.DisplayInOrder(Tree.rootPtr);
system("PAUSE");
return EXIT_SUCCESS;
}