您的位置:首页 > 其它

已知有序数组求最小深度二叉树

2013-09-16 14:16 337 查看
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>

typedef struct _tree_node
{
int m_nValue;
struct _tree_node *m_pLeft;
struct _tree_node *m_pRight;
}TreeNode;

TreeNode* createNode(int value)
{
TreeNode* pNode=(TreeNode *)malloc(sizeof(TreeNode));
assert(pNode!=NULL);
pNode->m_nValue=value;
pNode->m_pLeft=NULL;
pNode->m_pRight=NULL;
return pNode;
}

TreeNode* arrToTree(int *arr,int start,int end)
{
TreeNode *pHead=NULL;
if(end>=start)
{
int mid=(start+end)>>1;
pHead=createNode(arr[mid]);
pHead->m_pLeft=arrToTree(arr,start,mid-1);
pHead->m_pRight=arrToTree(arr,mid+1,end);
}
return pHead;
}

void printTree(TreeNode *pHead)
{
if(pHead==NULL)
return;
printTree(pHead->m_pLeft);
printf("%d ",pHead->m_nValue);
printTree(pHead->m_pRight);
}

int getTreeHeight(TreeNode *pHead)
{
if(pHead==NULL)
return 0;
return getTreeHeight(pHead->m_pLeft)>getTreeHeight(pHead->m_pRight)?getTreeHeight(pHead->m_pLeft)+1:getTreeHeight(pHead->m_pRight)+1;
}

int main()
{
int arr[]={0,1,2,3,4,5,6,7,8,9};
int len=sizeof(arr)/sizeof(arr[0]);
TreeNode *pHead=NULL;
pHead=arrToTree(arr,0,len-1);

printTree(pHead);

int hight=getTreeHeight(pHead);

printf("\n%d",hight);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐