Binary tree traversal
- Application of the binary tree, it is often required to find the node in the tree with certain features or nodes of the tree one by one subjected to a treatment, this presents a problem of how to traverse the binary tree.
- We want to visit each node in the tree according to a path search section, and that each node has, and is accessed only once . "Access" means a lot, may be a node for various processes, such as the output node information and the like. Linear traversal of the structure is easy to solve a problem, and for the binary tree is not the case, since the binary tree is a nonlinear structure, each node of which may have 0-2 subtrees, and therefore a need for a law, so that the nodes can be arranged on the binary tree on line queue to facilitate traversal.
- If we require to traverse here first left and right, then only three cases, namely root around, left and right root, root around, we are referred to preorder, preorder, postorder.
- The picture shows the two following two examples, and the results are given in the first order, in sequence, after traversal of:
- Here preorder, inorder, postorder recursive way I used to go to achieve, move in sequence as an example, the core code is the root of the left-right ideological :()
void inOrder(BiTree& T)
{
if(T)
{
inOrder(T->lchild);
visit(T->data);
inOrder(T->rchild);
}
}
- Here is a complete binary tree traversal implementation code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
//二叉链表的结点结构
typedef struct BiTreeNode{
char data; //数据域
struct BiTreeNode* lchild; //左孩子指针域
struct BiTreeNode* rchild; //右孩子指针域
}BiNode,*BiTree;
void CreateBiTree(BiTree& T); //初始化添加二叉树信息
void preOrder(BiTree& T); //先序遍历二叉树:根 左 右
void inOrder(BiTree& T); //中序遍历二叉树:左 根 右
void postOrder(BiTree& T); //后序遍历二叉树:左 右 根
void CreateBiTree(BiTree& T)
{
char ch;
cin>>ch;
if(ch=='#') T=NULL;
else
{
if(!(T=(BiNode*)malloc(sizeof(BiNode)))) exit(0);
T->data=ch;
//这里注意正确输入的顺序
CreateBiTree(T->lchild); //先构造左子树
CreateBiTree(T->rchild); //再构造右子树
}
}
int visit(char data1)
{
cout<<data1;
return 0;
}
void preOrder(BiTree& T)
{
if(T)
{
visit(T->data);
preOrder(T->lchild);
preOrder(T->rchild);
}
}
void inOrder(BiTree& T)
{
if(T)
{
inOrder(T->lchild);
visit(T->data);
inOrder(T->rchild);
}
}
void postOrder(BiTree& T)
{
if(T)
{
postOrder(T->lchild);
postOrder(T->rchild);
visit(T->data);
}
}
int main()
{
//测试用例:
//ABE##F##C#DG###
//-+a##*b##-c##d##/e##f##
BiTree T;
CreateBiTree(T);
preOrder(T);
cout<<endl;
inOrder(T);
cout<<endl;
postOrder(T);
return 0;
}
Results are as follows: