隔了好久,数据结构之树篇终于来啦!
还是C++实现,篇一介绍二叉树数组实现的前序遍历方式
具体看代码:
1、Tree.h
#ifndef TREE_H
#define TREE_H
class Tree
{
public:
Tree(int size, int *pRoot); //创建树
~Tree(); //销毁树
int *SearchNode(int nodeIndex); //根据索引寻找结点
bool AddNode(int nodeIndex, int direction, int *pNode); //添加结点
bool DeleteNode(int nodeIndex, int *pNode); //删除结点
void TreeTraverse(); //遍历结点
private:
int *m_pTree;
int m_iSize;
};
#endif
2、Tree.cpp
#include "Tree.h"
#include <iostream>
using namespace std;
Tree::Tree(int size, int *pRoot)
{
m_iSize = size;
m_pTree = new int[size];
for (int i = 0; i < size; i++)
{
m_pTree[i] = 0;
}
m_pTree[0] = *pRoot;
}
Tree::~Tree()
{
delete []m_pTree;
m_pTree = NULL;
}
int *Tree::SearchNode(int nodeIndex)
{
if (nodeIndex < 0 || nodeIndex >= m_iSize)
{
return NULL;
}
if (m_pTree[nodeIndex] == 0)
{
return NULL;
}
return &m_pTree[nodeIndex];
}
bool Tree::AddNode(int nodeIndex, int direction, int *pNode)
{
if (nodeIndex < 0 || nodeIndex >= m_iSize)
{
return false;
}
if (m_pTree[nodeIndex] == 0)
{
return false;
}
//向左边插入,新索引为父节点nodeIndex * 2 + 1
if (direction == 0)
{
if (nodeIndex * 2 + 1 < 0 || nodeIndex * 2 + 1 >= m_iSize)
{
return false;
}
if (m_pTree[nodeIndex * 2 + 1] != 0)//说明该节点已经存在值
{
return false;
}
m_pTree[nodeIndex * 2 + 1] = *pNode;
}
//向右边插入,新索引为父节点nodeIndex * 2 + 2
if (direction == 1)
{
if (nodeIndex * 2 + 2 < 0 || nodeIndex * 2 + 2 >= m_iSize)
{
return false;
}
if (m_pTree[nodeIndex * 2 + 2] != 0)//说明该节点已经存在值
{
return false;
}
m_pTree[nodeIndex * 2 + 2] = *pNode;
}
return true;
}
bool Tree::DeleteNode(int nodeIndex, int *pNode)
{
if (nodeIndex < 0 || nodeIndex >= m_iSize)
{
return false;
}
if (m_pTree[nodeIndex] == 0)
{
return false;
}
*pNode = m_pTree[nodeIndex];
m_pTree[nodeIndex] = 0;
return true;
}
void Tree::TreeTraverse()
{
for (int i = 0; i < m_iSize; i++)
{
cout << m_pTree[i] << " ";
}
}
3、测试代码Demo
#include <iostream>
#include "Tree.h"
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv)
{
int root = 3;
Tree *pTree = new Tree(10, &root);
int node1 = 5;
int node2 = 8;
pTree->AddNode(0, 0, &node1);
pTree->AddNode(0, 1, &node2);
int node3 = 2;
int node4 = 6;
int node5 = 9;
int node6 = 7;
pTree->AddNode(1, 0, &node3);
pTree->AddNode(1, 1, &node4);
pTree->AddNode(2, 0, &node5);
pTree->AddNode(2, 1, &node6);
pTree->TreeTraverse();
int *temp = pTree->SearchNode(2);
cout << endl << "node = " << *temp << endl;
int node = 0;
pTree->DeleteNode(6, &node);
cout << "deleteNode = " << node << endl;
pTree->TreeTraverse();
delete pTree;
return 0;
}
运行截图如下:
有关树的其他内容后续还会继续更新,通过代码联系能更好的加深理解
加油加油!!
如果代码当中有不太了解的,欢迎留言交流,一起学习~加油!
最后,简单了解一下概念吧。
偷懒了,笔记直接放上面了