1、二叉树节点的创建,每个节点间建立关联,打印每个节点,销毁二叉树完整代码:
#include <stdio.h>
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
BinaryTreeNode* m_pParent;
};
//创建新的节点
BinaryTreeNode* CreateBinaryTreeNode(int value)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nValue = value;
pNode->m_pLeft = NULL;
pNode->m_pRight = NULL;
pNode->m_pParent = NULL;
return pNode;
}
//节点间建立关联
void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
if(pParent != NULL)
{
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;
if(pLeft != NULL)
pLeft->m_pParent = pParent;
if(pRight != NULL)
pRight->m_pParent = pParent;
}
}
//打印每一个节点
void PrintTreeNode(BinaryTreeNode* pNode)
{
if(pNode != NULL)
{
printf("节点的值为: %d\n", pNode->m_nValue);
if(pNode->m_pLeft != NULL)
printf("节点的左孩子为: %d.\n", pNode->m_pLeft->m_nValue);
else
printf("左孩子为空.\n");
if(pNode->m_pRight != NULL)
printf("节点的右孩子为: %d.\n", pNode->m_pRight->m_nValue);
else
printf("右孩子为空.\n");
}
else
{
printf("节点为空.\n");
}
printf("\n");
}
//打印二叉树
void PrintTree(BinaryTreeNode* pRoot)
{
PrintTreeNode(pRoot);
if(pRoot != NULL)
{
if(pRoot->m_pLeft != NULL)
PrintTree(pRoot->m_pLeft);
if(pRoot->m_pRight != NULL)
PrintTree(pRoot->m_pRight);
}
}
//销毁二叉树
void DestroyTree(BinaryTreeNode* pRoot)
{
if(pRoot != NULL)
{
BinaryTreeNode* pLeft = pRoot->m_pLeft;
BinaryTreeNode* pRight = pRoot->m_pRight;
delete pRoot;
pRoot = NULL;
DestroyTree(pLeft);
DestroyTree(pRight);
}
}
//测试代码:
void Test()
{
//创建节点
BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);
//建立关联
ConnectTreeNodes(pNode8, pNode6, pNode10);
ConnectTreeNodes(pNode6, pNode5, pNode7);
ConnectTreeNodes(pNode10, pNode9, pNode11);
//打印二叉树
PrintTree(pNode8);
//销毁二叉树
DestroyTree(pNode8);
}
int main()
{
Test();
return 0;
}
2、测试结果如下: