树结构的定义,几种遍历方法

来源:互联网 发布:推理小说推荐 知乎 编辑:程序博客网 时间:2024/05/18 00:47

1、数据结构中树结构体的定义:

typedef struct BinaryTreeNode{int data;struct BinaryTreeNode *lchild;struct BinaryTreeNode *rchild;}* BinTreeRoot;
定义了BinaryTreeNode这个结构体是树中的一个节点。然后又使用typedef将BinaryTreeNode的指针封装为BinTreeRoot类型,相当于是

typedef struct BinaryTreeNode * BinTreeRoot.
2、给定一个指向根节点的指针,树的遍历过程

(1)先序遍历(先根遍历)

递归实现:

void preOrder(BinaryTreeNode *pRoot){if(pRoot == NULL)return;else{cout << pRoot->data << " ";preOrder(pRoot->lchild);preOrder(pRoot->rchild);}}


借助于栈实现:

void preOrderStack(BinaryTreeNode *pRoot){if (pRoot == NULL)return;stack<BinaryTreeNode *>s;s.push(pRoot);while (!s.empty()){BinaryTreeNode *temp = s.top();s.pop();cout << temp->data << " ";if (temp->rchild != NULL)s.push(temp->rchild);if (temp->lchild != NULL)s.push(temp->lchild);}}




(2)中序遍历(中根遍历)

递归实现:

void inOrder(BinaryTreeNode *pRoot){if (pRoot == NULL)return;else{inOrder(pRoot->lchild);cout << pRoot->data << " ";inOrder(pRoot->rchild);}}



借助于栈实现:

void inOrderStack(BinaryTreeNode *pRoot){if (pRoot == NULL)return;BinaryTreeNode *p = pRoot;stack<BinaryTreeNode *>s;s.push(p);//将根节点入栈BinaryTreeNode *temp = p->lchild;while (temp != NULL)//将这棵树左边的入栈{s.push(temp);temp = temp->lchild;}while (!s.empty()){temp = s.top();s.pop();cout << temp->data << " ";if (temp->rchild != NULL){temp = temp->rchild;while (temp){s.push(temp);temp = temp->lchild;}}}}




(3)后序遍历(后根遍历)

递归实现

void postOrder(BinaryTreeNode *pRoot){if (pRoot == NULL)return;else{postOrder(pRoot->lchild);postOrder(pRoot->rchild);cout << pRoot->data << " ";}}



(4)层次遍历(广度优先遍历)

void herOrder(BinaryTreeNode *root){if (root == NULL)return;queue<BinaryTreeNode *>q;q.push(root);while (!q.empty()){BinaryTreeNode *temp = q.front();q.pop();cout << temp->data << " ";if (temp->lchild)q.push(temp->lchild);if (temp->rchild)q.push(temp->rchild);}}

把树看做图,相当于图中广度优先遍历。使用队列的先进先出的性质。在图的广度优先遍历中需要设定一个指示节点是否进过队列的bool变量。如果进过队列就置为true,如果没有进过队列为false。

广度优先遍历的思想就是:出对一个元素,将与出对元素相邻并且未进过队列的元素进队这样一个过程。