用数组创建二叉树的一种方法

来源:互联网 发布:唐软网络是培训吗 编辑:程序博客网 时间:2024/06/11 03:51

很多面试题都是二叉树相关的, 因此经常需要测试自己的写的程序, 那么创建二叉树就必不可少, 用数组中的值初始化二叉树是一种比较简单的方法.



typedef struct BSTreeNode{
int m_nValue;
struct BSTreeNode * m_pLeft;
struct BSTreeNode * m_pRight;
}BSTreeNode;


BSTreeNode * creatBTree(int data[], int index, int n)  
{
BSTreeNode * pNode = NULL;

if(index < n && data[index] != -1)  //数组中-1 表示该节点为空
{
pNode = (BSTreeNode *)malloc(sizeof(BSTreeNode));
if(pNode == NULL)
return NULL;
pNode->m_nValue = data[index];
pNode->m_pLeft = creatBTree(data, 2 * index + 1, n);  //将二叉树按照层序遍历, 依次标序号, 从0开始
pNode->m_pRight = creatBTree(data, 2 * index + 2, n);
}

return pNode;
}

0 0
原创粉丝点击