学习的过程是一个由浅入深,由表及里的过程,今天来浅谈以下数据结构之二叉树,究竟是怎么写出来的。
代码如下:
BinaryTreeNode.h文件
#pragma once
#include<iostream>
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* CreateBinaryTreeNode(int value);
void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight);
void PrintTreeNode(const BinaryTreeNode* pNode);
void PrintTree(const BinaryTreeNode* pRoot);
void DestroyTree(BinaryTreeNode* pRoot);
在头文件中,首先定义一个二叉树结点的定义。其中,二叉树主要有数据域和指针域两个域构成,指针指向两个其余的子节点,数据存放当前结点的数据。然后,包含一些辅助函数的声明。
BinaryTreeNode.cpp文件
#include"BinaryTree.h"
BinaryTreeNode* CreateBinaryTreeNode(int value) {
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nValue = value;
pNode->m_pLeft = nullptr;
pNode->m_pRight = nullptr;
return pNode;
}
void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight) {
if (pParent != nullptr) {
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;
}
}
void PrintTreeNode(const BinaryTreeNode* pNode) {
if (pNode != nullptr)
{
printf("value of this node is: %d\n", pNode->m_nValue);
if (pNode->m_pLeft != nullptr)
printf("value of its left child is: %d.\n", pNode->m_pLeft->m_nValue);
else
printf("left child is nullptr.\n");
if (pNode->m_pRight != nullptr)
printf("value of its right child is: %d.\n", pNode->m_pRight->m_nValue);
else
printf("right child is nullptr.\n");
}
else
{
printf("this node is nullptr.\n");
}
printf("\n");
}
void PrintTree(const BinaryTreeNode* pRoot) {
PrintTreeNode(pRoot);
if (pRoot != nullptr)
{
if (pRoot->m_pLeft != nullptr)
PrintTree(pRoot->m_pLeft);
if (pRoot->m_pRight != nullptr)
PrintTree(pRoot->m_pRight);
}
}
void DestroyTree(BinaryTreeNode* pRoot) {
if (pRoot != nullptr)
{
BinaryTreeNode* pLeft = pRoot->m_pLeft;
BinaryTreeNode* pRight = pRoot->m_pRight;
delete pRoot;
pRoot = nullptr;
DestroyTree(pLeft);
DestroyTree(pRight);
}
}
以上为相关辅助函数的实现。
main.cpp文件
#include"BinaryTree.h"
int main() {
BinaryTreeNode* btNode1 = CreateBinaryTreeNode(1);
BinaryTreeNode* btNode2 = CreateBinaryTreeNode(2);
BinaryTreeNode* btNode3 = CreateBinaryTreeNode(3);
BinaryTreeNode* btNode4 = CreateBinaryTreeNode(4);
ConnectTreeNodes(btNode1, btNode2, btNode3);
ConnectTreeNodes(btNode3, btNode4, nullptr);
PrintTree(btNode1);
DestroyTree(btNode1);
return 0;
}
主函数中定义了四个结点,结构如下
1
/ \
2 3
/
4
先创建结点,利用参数初始化数据域,然后将指针初始化问nullptr;
其次,利用辅助函数将各结点连接起来。
然后,将二叉树整体打印输出,其中利用了递归结构
最后,将在堆区开辟的内存释放。
程序运行结束。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/130585.html