本文主要是介绍数据冒险之二叉树(数组),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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
Tree.cpp
#include<iostream>
#include"Tree.h"
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;}if (direction==0) //0代表左边{if (2 * nodeIndex + 1 >= m_iSize){return false;}if (m_pTree[2 * nodeIndex + 1] != 0) //已经有了左结点{return false;}m_pTree[2 * nodeIndex + 1] = *pNode;}if (direction == 1) //1代表右边{if (2 * nodeIndex + 2 >= m_iSize){return false;}if (m_pTree[2 * nodeIndex + 2] != 0) //已经有了右结点{return false;}m_pTree[2 * nodeIndex + 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] << " ";}}
main.cpp
#include<iostream>
#include"Tree.h"
using namespace std;
/*****************************************/
/* 二叉树(数组表示)关于数据与树之间的算法转换int tree[n] 3 5 8 2 6 9 73(0)5(1) 8(2)2(3) 6(4) 9(5) 7(6)结论:
父亲节点下标*2+1 为该节点左孩子的下标
父亲节点下标*2+2 为该节点右孩子的下标
*/
int main()
{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;pTree->AddNode(1, 0, &node3);pTree->AddNode(1, 1, &node4);int node5 = 9;int node6 = 7;pTree->AddNode(2, 0, &node5);pTree->AddNode(2, 1, &node6);pTree->TreeTraverse();int node = 0;pTree->DeleteNode(6, &node);cout << endl << "删除的结点node=" << node << endl;pTree->TreeTraverse();int *p=pTree->SearchNode(2); //搜寻下标为2的结点cout <<endl<< "下标为2的结点node="<< *p << endl;delete pTree;return 0;
}
这篇关于数据冒险之二叉树(数组)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!