General Tree

  1. 相关术语及定义:

    (1)Root: 树T是由一个或一个以上的结点组成的有限集,R称为根节点
    (2)Subtree: 集合(T-|R|)非空时,集合中结点被划分成n个不相交的子集,每个子集都是树,子集Ti称为T的subtree,定义i < j,Ti位于Tj之前,T0为最左子节点
    (3)结点的子结点数目:该结点的出度(out degree)
    (4)forest: 1/n颗树
    (5)ancestor: 当前节点的所有上层结点
    (6)siblings: 当前结点同父的兄弟结点
    (7)path: 如果有一串结点n1,n2…..nk,叫做n1到nk的路径
    (8)length:路径长为k-1
    (9)depth:结点M的深度是根节点到M的路径长度 m-1,与level/层数相等,根节点层数为0 深度为0
    (10)height:树的高度等于最深的结点度数加一
    (11)leaf: 没有空子树的结点是叶结点
    (12)internal node: 至少有一个非空子树的结点称为内部结点或分支结点

这里写图片描述

  1. General Tree ADT

// General tree node ADT
template < typename E> class GTNode {
public:
E value(); // Return node’s value
bool isLeaf(); // True if node is a leaf
GTNode* parent(); // Return parent
GTNode* leftmostChild(); // Return first child
GTNode* rightSibling(); // Return right sibling
void setValue(E&); // Set node’s value
void insertFirst(GTNode< E >*); // Insert first child
void insertNext(GTNode< E >*); // Insert next sibling
void removeFirst(); // Remove first child
void removeNext(); // Remove right sibling
};

//genernal tree ADT
template < typename E>
class GenTree {
public:
void clear(); //send all nodes to free store
GTNode< E>* root(); //return the root of the tree
//combine two subtrees
void newroot(E&,GTNode< E>* ,GTNode< E>*);
void print(); //print a tree
};

3.General Tree traversal_recursion

void printAtPre(GTNode< E>* root)//print a tree as preorder
{
if(root->isLeaf())
cout<<”Leaf: “;
else
cout<<”Internal: “;
cout<< root->value()<< endl;
//now process the children of “root”
for(GTNode< E >* temp = root->leftmostChild();
temp!=null;temp = temp->rightSibling())
printAtPre(temp);
}

按照先根遍历打印树中所有节点,末尾的for循环用于处理每个子结点,先从最左子结点开始,依次处理,直到最后返回NULL终止

4.Parent Pointer Implementation
(1)定义:对每个结点只保存一个指针域指向其父节点
(2)用途:

  • 判定结点是否位于同一个树中->顺着结点的父指针追溯到根节点,如果到达同一个,则成立
  • 维护不相交子集构成的集合:几个不相交的集合可以划分一组结点,使得每个结点属于且只属于其中一个集合
    • 需要操作->并查集(UNION/FIND):1. 判断两个结点是否位于同一个集合中
      2. 归并两个集合

(3)FIND:查找一个给定结点的根节点的过程
(4)树的并查算法的实现

//General tree representation for UNION/FIND by parent point
class ParPtrTree{
private:
int* array; //Node array
int size; //Size of node array,store the parentptr’s statement
int FIND(int) const; //Find root

public:
ParPtrTree(int); //Constructor
~ParPtrTree(){
delete [] array;
} //Destructor
void UNION(int,int); //Merge equivalences
bool differ(int,int); //True if not in the same tree
}

int ParPtrTree::FIND(int curr) const{ //find root
while (array[curr] !=Root) curr=array[curr];
return curr; //at root
}

猜你喜欢

转载自blog.csdn.net/zerlina98/article/details/78633036