1、树的基本知识
树的介绍
各种树
2、无序树的插入(利用链表实现)
什么是无序树?
将树中各个子树看成从左到右有次序的,不能互换的,则成为有序树,否则就是无序树。
关于树的插入,逻辑上较为简单,但是实现起来较为复杂。具体的操作步骤为:首先,为新的节点开辟一块内存,并将所有数据置为空,接着将需要插入的数据赋给新节点指向的数据。接下分为2种情况分析:1、根节点已经存在;2、根节点不存在。
当根节点不存在,则将插入的节点作为根节点。
当根节点已经存在,接着就是需要寻找插入节点前一个节点数据目前在哪里。这里又分为2种情况:1、可以找到;2、不可已找到。
当可以找到,判断该节点是否有子节点,有子节点就插入到子节点末尾。没有子节点就,以该节点的兄弟节点插入。
当没有找到,插入到树的末尾位置。
(1).h文件
#pragma once
#include <memory>
template <class T>
class Tree
{
struct TreeNode
{
T data; //数据
TreeNode* parent; //父节点
TreeNode* child; //孩子节点
TreeNode* brother; //兄弟节点
};
public:
Tree();
~Tree();
//插入一个节点
//perNodeData,前节点(并不一定是父节点)
//insertData 需要被插入的数据
//是否是perNodeData节点的孩子节点
void InsertNode(const T& perNodeData, const T& insertData, bool bChild);
//删除节点,删除某个节点,删除该节点和他所有的子节点,兄弟节点不删
void deleteNode(const T& delData);
private:
//在root树中查找某个节点
//如果找到了,返回该节点的指针,如果找不到,返回0
TreeNode* _findNode(TreeNode* root, const T& findData);
private:
TreeNode* pRoot; //根节点
};
template <class T>
Tree<T>::Tree()
{
pRoot = 0;
}
template <class T>
Tree<T>::~Tree()
{
}
template <class T>
void Tree<T>::InsertNode(const T& perNodeData, const T& insertData, bool bChild)
{
//生产一个新节点
TreeNode* pNewNode = new TreeNode;
memset(pNewNode, 0x00, sizeof(TreeNode));
pNewNode->data = insertData;
//判断有无根节点
if (pRoot)
{
//找到perNodeData所在的节点
TreeNode* pFindNode = _findNode(pRoot, perNodeData);
//如果节点有找到
if (pFindNode)
{
//是否是作为child节点进行插入,如果,则插入到pFindNode节点的孩子处,
//如果pFindNode本身有孩子,则作为最后的孩子节点
if (bChild)
{
pNewNode->parent = pFindNode; //找到的节点,作为新节点的父节点
TreeNode* temp = pFindNode->child;
if (temp) //如果原来就还有孩子节点
{
while (temp->brother) //通过循环,temp将会指向最后一个孩子
temp = temp->brother;
temp->brother = pNewNode;
}
else //没有孩子
{
pFindNode->child = pNewNode;
}
}
else //作为兄弟节点,进行插入
{
pNewNode->brother = pFindNode->brother;
pFindNode->brother = pNewNode;
pNewNode->parent = pFindNode->parent; //是兄弟,父节点是同一个
}
}
else //如果节点没有找到, 则插入到树的末尾
{
TreeNode* temp = pRoot;
while (temp->child)
temp = temp->child;
temp->child = pNewNode;
pNewNode->parent = temp;
}
}
else //没有根节点, 则插入的节点为根节点
{
pRoot = pNewNode;
}
}
template <class T>
void Tree<T>::deleteNode(const T& delData)
{
}
//计算A阶乘, A! = A * (A - 1)!
template <class T>
typename Tree<T>::TreeNode* Tree<T>::_findNode(TreeNode* root, const T& findData)
{
if (root)
{
//如果root节点中数据就是我们要找的数据,则表示找到该节点
if (root->data == findData)
return root;
//如果不是我们要找的节点,则找他的孩子和兄弟
TreeNode* pTemp = 0;
pTemp = _findNode(root->child, findData);
if (pTemp) return pTemp;
pTemp = _findNode(root->brother, findData);
if (pTemp) return pTemp;
}
return 0;
}
(2).cpp文件
#include "stdafx.h"
#include "tree.h"
int _tmain(int argc, _TCHAR* argv[])
{
Tree<int> intTree;
intTree.InsertNode(1, 5, 1); //插入根节点
intTree.InsertNode(5, 3, 1);
intTree.InsertNode(3, 9, 0);
intTree.InsertNode(9, 8, 0);
intTree.InsertNode(8, 1, 0);
intTree.InsertNode(3, 10, 1);
intTree.InsertNode(8, 4, 1);
intTree.InsertNode(4, 6, 0);
intTree.InsertNode(4, 11, 1);
intTree.InsertNode(9, 7, 0);
intTree.InsertNode(12, 13, 0);
return 0;
}