算法c++之二叉树广度遍历和深度遍历

算法c++之二叉树广度遍历和深度遍历

1、深度遍历
struct Tree{
    
    
	int data;
	struct Tree *lchild,rchild;
}BiTree;
  • 先序遍历(中左右)
void PreOrderTraverse(BiTree *T)  
{
    
      
    if(T){
    
      
        printf("%c ",T->data);  
        PreOrderTraverse(T->lchild);  
        PreOrderTraverse(T->rchild);  
    }  
}  
  • 中序遍历 (左中右)
void InOrderTraverse(BiTree *T)  
{
    
      
    if(T){
    
      
        InOrderTraverse(T->lchild);  
        printf("%c ",T->data);  
        InOrderTraverse(T->rchild);  
    }  
}  
  • 后序遍历 (左右中)
void PostOrderTraverse(BiTree *T)  
{
    
      
    if(T){
    
      
        PostOrderTraverse(T->lchild);  
        PostOrderTraverse(T->rchild);  
        printf("%c ",T->data);  
    }  
}
2、广度遍历
void LevelOrder(BiTree *root) {
    
    
	if(root == NULL) return;
	queue<binode*> Q;
	Q.push(root);
	//while there is at least one discovered node
	while(!Q.empty()) {
    
    
		BiTree * current = Q.front();
		Q.pop(); // removing the element at front
		cout<<current->data<<" ";
		if(current->lchild != NULL) Q.push(current->lchild);
		if(current->rchild != NULL) Q.push(current->rchild);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_45125250/article/details/109771359