Binary tree traversal method

reference

  1. "Dahua Data Structure"
  2. This note is only for learning records

1. Preorder traversal

Rule: Follow the way of accessing the root first, then the left subtree, and finally the right subtree (root->left->right)
Insert picture description here

// 前序遍历
void PreOrderTraverse(BiTree T)
{
    
    
	if(T==NULL)
		return ;
	printf("%c",T->data); // 显示结点数据,也可以是其他操作
	PreOrderTraverse(T->lchild);
	PreOrderTraverse(T->rchild); 
} 

Access sequence: ABDGHCEIF

In-order traversal

Rule: Visit the left subtree first, then the root node ( refers to the root node of the current subtree, not the root node of the entire tree ), and finally the right subtree (left->root->right)

As shown in the figure, in the subtree marked by the yellow box, D is the root node of the subtree
Insert picture description here

// 中序遍历 
void InOrderTraverse(BiTree T)
{
    
    
	if(T==NULL)
		return ;
	InOrderTraverse(T->lchild);
	printf("%c",T->data);
	InOrderTraverse(T->rchild);
} 

Access sequence: GDHBAEICF

Subsequent traversal

Rule: Follow the order of the left subtree first, then the right subtree, and the last root node (still the root node of the current subtree) (left->right->root)
Insert picture description here

// 后序遍历
void PostOrderTraverse(BiTree T)
{
    
    
	if(T==NULL)
		return ;
	PostOrderTraverse(T->lchild);
	PostOrderTraverse(T->rchild);
	printf("%c",T->data);
} 

Access sequence: GHDBIEFCA

In fact, the so-called pre, middle, and post order refer to the order in which the roots are visited. As in the previous order, the root is visited first, and in the middle order, the root is visited second.

Sequence traversal

The layer sequence traversal starts from the follow node, layer by layer, and scans from left to right for each layer.
Insert picture description here

Access sequence: ABCDEFGHL

void LevelOrder(BiTree b)
{
    
     
	InitQueue(Q); 
	BiTree p; 
	EnQueue(Q,b); //根结点进队 
	while(IsEmpty(Q))
	{
    
               
	//队列不空循环 
	DeQueue(Q,p) 
	//队头元素出队 
	printf(%c”,p->data); 
	if(p->lchild!=NULL) 
	EnQueue(Q,p->lchild); 
	if(p->rchild!=NULL) 
	EnQueue(Q,p->rchild); 
	} 
}

**note

  1. The layer sequence traversal is very similar to the breadth-first traversal of the graph in the algorithmic idea.**

Guess you like

Origin blog.csdn.net/qq_34902437/article/details/94012432