没什么好的想法,只是递归,强行搞定。
代码如下:
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct BinaryTree
{
int data;
BinaryTree *left;
BinaryTree *right;
}*PointerTree;
void InsertBinaryTree(BinaryTree *root,int data)
{
BinaryTree *temp = root;
BinaryTree *parent = NULL;
while(temp != NULL)
{
parent = temp;
if(temp->data < data)
temp = temp->right;
else if(temp->data > data)
temp = temp->left;
else
return;
}
BinaryTree *keytemp = (BinaryTree*)malloc(sizeof(BinaryTree));
keytemp->data = data;
keytemp->left = NULL;
keytemp->right = NULL;
if(parent != NULL)
{
if(data > parent->data)
parent->right = keytemp;
else
parent->left = keytemp;
}
}
int maxheight(int x,int y)
{
return ((x > y) ? x : y);
}
int BinaryTreeHeight(BinaryTree *root)
{
if(root == NULL)
return 0;
return (1 + maxheight(BinaryTreeHeight(root->left),BinaryTreeHeight(root->right)));
}
int main()
{
BinaryTree *root = (BinaryTree*)malloc(sizeof(BinaryTree));
root->data = 9;
root->left = NULL;
root->right = NULL;
InsertBinaryTree(root,8);
InsertBinaryTree(root,7);
InsertBinaryTree(root,6);
InsertBinaryTree(root,5);
InsertBinaryTree(root,4);
InsertBinaryTree(root,3);
InsertBinaryTree(root,2);
InsertBinaryTree(root,11);
cout<<"The height of binarytree is "<<BinaryTreeHeight(root)<<endl;
return 0;
}