【100题】第四十二题 二叉树的非递归遍历

二叉树遍历
本文介绍了二叉树的非递归遍历方法,包括前序、中序和后序遍历的具体实现。通过栈来辅助完成遍历过程,确保正确访问每一个节点。

一,前序遍历非递归:

根据前序遍历访问的顺序,优先访问根结点,然后再分别访问左孩子和右孩子。即对于任一结点,其可看做是根结点,因此可以直接访问,访问完之后,若其左孩子不为空,按相同规则访问它的左子树;当访问其左子树时,再访问它的右子树。因此其处理过程如下:

对于任一结点P:

1)访问结点P,并将结点P入栈;

2)判断结点P的左孩子是否为空,若为空,则取栈顶结点并进行出栈操作,并将栈顶结点的右孩子置为当前的结点P,循环至1);若不为空,则将P的左孩子置为当前的结点P;

3)直到P为NULL并且栈为空,则遍历结束。

void preOrder2(node *root) //非递归前序遍历

{

stack<node*> s;

node *p=root;

while(p!=NULL||!s.empty())

{

while(p!=NULL)//向左遍历直到叶子

{

cout<<p->data<<" ";

s.push(p);

p=p->lchild;

}

if(!s.empty())

{

p=s.top();

s.pop();

p=p->rchild;

}

}

cout<<endl;

}

二,中序遍历非递归

根据中序遍历的顺序,对于任一结点,优先访问其左孩子,而左孩子结点又可以看做一根结点,然后继续访问其左孩子结点,直到遇到左孩子结点为空的结点才进行访问,然后按相同的规则访问其右子树。因此其处理过程如下:

对于任一结点P,

1)若其左孩子不为空,则将P入栈并将P的左孩子置为当前的P,然后对当前结点P再进行相同的处理;

2)若其左孩子为空,则取栈顶元素并进行出栈操作,访问该栈顶结点,然后将当前的P置为栈顶结点的右孩子;

3)直到P为NULL并且栈为空则遍历结束

void inOrder2(node *root) //非递归中序遍历

{

stack<node*> s;

node *p=root;

while(p!=NULL||!s.empty())

{

while(p!=NULL)//记录访问过的根节点

{

s.push(p);

p=p->lchild;

}

if(!s.empty())

{

p=s.top();

cout<<p->data<<" "; //访问栈顶

s.pop();

p=p->rchild; //将当前访问的元素的右孩子入栈

}

}

}

要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。如果P不存在左孩子和右孩子,则可以直接访问它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。

void postOrder3(node *root) //非递归后序遍历

{

stack<node*> s;

node *cur; //当前结点

node *pre=NULL; //前一次访问的结点

s.push(root);

while(!s.empty())

{

cur=s.top();

if((cur->lchild==NULL&&cur->rchild==NULL)||

(pre!=NULL&&(pre==cur->lchild||pre==cur->rchild)))

{

cout<<cur->data<<" "; //如果当前结点没有孩子结点或者孩子节点都已被访问过

s.pop();

pre=cur;

}

else

{

if(cur->rchild!=NULL)

s.push(cur->rchild);

if(cur->lchild!=NULL)

s.push(cur->lchild);

}

}

}

综合程序附录

#include "stdio.h"
#include "stdlib.h" 
#include "stack.h"
int count;//统计叶子节点个数 
struct node
{
	int data;//二叉树的节点值
	node *lchild,*rchild;//左右孩子节点 
};
/*不知道为什么 创建的时候需要返回值才 创建有效*/
node *createTree()
{
	node *root;
	int data;
	printf("input data:");
	scanf("%d",&data);
	//printf("output data:%d\n",data);
	
	if(data==0)
	  root=NULL;
    else/*根左右 前序建立二叉树*/
    {
    	root=(node*)malloc(sizeof(node));
    	root->data=data;
    	root->lchild=createTree();
    	root->rchild=createTree();	
    }
	return root;
} 
void preOrder(node *root)
{
	if(root==NULL)
       	 return;
	else//不是空
	{
		printf("%d\n",root->data);
		preOrder(root->lchild);
		preOrder(root->rchild); 
	} 

}
void inOrder(node *root)
{
	if(root==NULL)
       	 return;
	else//不是空
	{
		
		inOrder(root->lchild);
		printf("%d\n",root->data);
		inOrder(root->rchild); 
	} 

}
void postOrder(node *root)
{
	if(root==NULL)
       	 return;
	else//不是空
	{
		postOrder(root->lchild);
		postOrder(root->rchild);
		printf("%d\n",root->data); 
	} 

}
void  CountLeaves(node *root)
{
	if(root==NULL)
       	 return;
	else//不是空
	{
		if(root->lchild==NULL&&root->rchild==NULL)
		     count++;
		CountLeaves(root->lchild);
		CountLeaves(root->rchild); 
	} 
	
} 
int deepLength(node *root)
{
	int deep1,deep2;
	if(root==NULL)
	    return 0;
    else
    {
    	deep1=deepLength(root->lchild);
    	deep2=deepLength(root->rchild);
    	if(deep1>deep2)
    	     return deep1+1;//这个地方一定是返回+1 
        else
             return deep2+1;
    }
	
}
void  CountNodes(node *root)
{
	if(root==NULL)
       	 return;
	else//不是空
	{		
        count++;
		CountNodes(root->lchild);
		CountNodes(root->rchild); 
	} 
	
} 
void exchange(node *root)
{
	
	if(root==NULL)
	   return;
    else
    {
    	exchange(root->lchild);
    	exchange(root->rchild);
    	node *temp=root->lchild;
    	root->lchild=root->rchild;
    	root->rchild=temp;
    	
    }
}
void search(node *root,int x)
{

	if(root==NULL)
	    return ;
    else
       {
       	  if(root->data==x)
       	     {
     	       	count++;  
     	       	printf("has\n");
     	       }      
   	      search(root->lchild,x);
	      search(root->rchild,x);
       }
}

void preOrder2(node *root)     //非递归前序遍历 
{
    stack<node*> s;
    node *p=root;
    while(p!=NULL||!s.empty())
    {
        while(p!=NULL)//向左遍历 直到叶子 
        {
            cout<<p->data<<" ";
            s.push(p);
            p=p->lchild;
        }
        if(!s.empty())
        {
            p=s.top();
            s.pop();
            p=p->rchild;
        }
    }
    cout<<endl; 
}
void inOrder2(node *root)      //非递归中序遍历
{
    stack<node*> s;
    node *p=root;
    while(p!=NULL||!s.empty())
    {
        while(p!=NULL)
        {
            s.push(p);
            p=p->lchild;
        }
        if(!s.empty())
        {
            p=s.top();
            cout<<p->data<<" ";
            s.pop();
            p=p->rchild;
        }
    }    
}
void postOrder3(node *root)     //非递归后序遍历
{
    stack<node*> s;
    node *cur;                      //当前结点 
    node *pre=NULL;                 //前一次访问的结点 
    s.push(root);
    while(!s.empty())
    {
        cur=s.top();
        if((cur->lchild==NULL&&cur->rchild==NULL)||
           (pre!=NULL&&(pre==cur->lchild||pre==cur->rchild)))
        {
            cout<<cur->data<<" ";  //如果当前结点没有孩子结点或者孩子节点都已被访问过 
              s.pop();
            pre=cur; 
        }
        else
        {
            if(cur->rchild!=NULL)
                s.push(cur->rchild);
            if(cur->lchild!=NULL)    
                s.push(cur->lchild);
        }
    }    
}

/*一定要记住直接输入1 2 3 0 0 0 0 建立的是 左二叉树 平衡的应该是 1 2 0 0 3 0 0*/
int main()
{
	node *root;//=(node*)malloc(sizeof(node));//这里不要初始化了 因为建立的时候要初始化 
	printf("             Please select what you  want do\n");
	printf("----------------------------------------------\n");
	printf("    1.前序创建二叉树\n");
	printf("    2.递归前序遍历二叉树\n");
	printf("    3.递归中序遍历二叉树\n");
	printf("    4.递归后序遍历二叉树\n");
	printf("    5.求叶节点个数\n");
	printf("    6.求树的高度\n");
	printf("    7.求二叉树节点个数\n");
	printf("    8.交换左右子树\n");
	printf("    9.查找有无某个节点\n");
	printf("    10.非递归前序遍历二叉树\n");
	printf("    11.非递归前序遍历二叉树\n");
	printf("    12.非递归前序遍历二叉树\n");
	printf("    15.退出\n");
	 
	int i;
	
	while(true)
	{
		scanf("%d",&i);
     	switch(i)
	    {
	    	case 1: root=createTree();
			        printf("create tree is finished please select what you want do next:\n");break;
	    	case 2:	printf("Now outPut data in PreOrder:\n");
	                preOrder(root);
	                printf("output is over please select again\n");break;
	    	case 3: printf("Now outPut data in inOrder:\n");
	                inOrder(root);
					printf("output is over please select again\n");break;
	    	case 4: printf("Now outPut data in postOrder:\n");
	                postOrder(root);
					printf("output is over please select again\n");break;
	    	case 5: count=0;
	    	        CountLeaves(root);
                    printf("The leaves's count is:%d\n",count);
					printf("output is over please select again\n");break;//叶子节点的个数 
	    	case 6: int deep=deepLength(root);
                    printf("The tree's deepLength is:%d\n",deep);
					printf("output is over please select again\n");break;
	    	case 7: count=0;
	    	        CountNodes(root);
                    printf("The leaves's count is:%d\n",count);
					printf("output is over\n"); 
			        break;//求二叉树节点个数 
	    	case 8: exchange(root);
			        break;
            case 9: printf("please input what you want search\n");
                    int x;
                    scanf("%d",&x);
                    count=0;
                    search(root,x);
					if(count!=0)
                       {
					      printf("The tree has this root\n");
                          printf("output is over please select again\n");
                       }
                    else
                       {
					      printf("The tree not has this root\n");
					      printf("output is over please select again\n");
                       }
			        break;
            case 10:	printf("Now outPut data in PreOrder:\n");
	                preOrder2(root);
	                printf("output is over please select again\n");break;
            case 11:	printf("Now outPut data in PreOrder:\n");
	                inOrder2(root);
	                printf("output is over please select again\n");break;
            case 12:	printf("Now outPut data in PreOrder:\n");
	                postOrder3(root);
	                printf("output is over please select again\n");break;
	                
	    	case 15: exit(0); break;//包含在stdlib.h当中 
		
        }   
	} 
	
	return 0;
}


 

                
Description 用函数实现如下(平衡)二叉排序树算法: (1) 插入新结点 (2) 前序、中序、后序遍历二叉树 (递归) (3) 前序、中序、后序遍历非递归算法 (4) 层次遍历二叉树 (5) 在二叉树中查找给定关键字(函数返回值为成功1,失败0) (6) 交换各结点的左右子树 (7) 求二叉树的深度 (8) 叶子结点数 (9) 删除某结点 输入格式 第一行:准备建树的结点个数n 第二行:输入n个整数,用空格分隔 第三行:输入待查找的关键字 第四行:输入待查找的关键字 第五行:输入待插入的关键字 第六行:输入待删除的关键字 输出格式 第一行:二叉树的先序遍历序列 第二行:二叉树的中序遍历序列 第三行:二叉树的后序遍历序列 第四行:查找结果 第五行:查找结果 第六行~第八行:插入新结点后的二叉树的先、中、序遍历序列 第九行:插入新结点后的二叉树的中序遍历序列(非递归算法) 第十行:插入新结点后的二叉树的层次遍历序列 第十一行:删除结点后的二叉树的中序遍历序列(非递归算法) 第十二行:删除结点后的二叉树的层次遍历序列 第十三行~第十五行:第一次交换各结点的左右子树后的先、中、后序遍历序列 第十六行~第十八行:第二次交换各结点的左右子树后的先、中、后序遍历序列 第十九行:二叉树的深度 第二十行:叶子结点数
最新发布
06-06
<think>目要求实现平衡二叉排序树(AVL树)的各种操作,并且输出格式要求严格。我们需要注意以下几点:1.输入:第一行是结点个数n,第二行是n个整数,第三行和第四行是两个待查找的关键字,第五行是待插入的关键字,第六行是待删除的关键字(这是新增的,注意目描述中第六行是待删除关键字)2.输出:有20行输出,按照要求输出各种遍历结果。我们使用AVL树来实现。AVL树在插入和删除时通过旋转操作保持平衡。需要实现以下函数:-插入(包括旋转操作)-删除(也包括旋转操作)-三种递归遍历(前序、中序、后序)-三种非递归遍历(前序、中序、后序)——注意目要求输出插入新结点后的中序遍历非递归)和删除结点后的中序遍历非递归)-层次遍历(使用队列)-查找-交换左右子树(递归进行)-求深度-叶子结点计数注意:目要求删除结点,所以我们需要实现删除操作。步骤:1.定义AVL树结点结构(包含值、高度、左右子结点指针)。2.实现基本的辅助函数:获取结点高度、更新高度、平衡因子计算。3.实现旋转函数:右旋、左旋。4.实现插入函数(递归),在递归回溯过程中更新高度并检查平衡,进行必要的旋转。5.实现删除函数(递归),同样需要更新高度和平衡。6.实现各种遍历(递归和非递归)。7.主函数中按顺序处理输入,构建AVL树,进行各种操作并输出。注意:交换左右子树操作,我们采用递归方式,交换每个结点的左右子树。注意交换两次可以恢复原树。由于目要求输出步骤较多,我们严格按照输出格式进行。注意:在删除结点后,我们还需要输出删除后的非递归中序遍历和层次遍历,然后再进行交换操作。另外,目要求两次交换子树后输出遍历序列。注意:第一次交换后,树的结构改变;第二次交换(相当于再次交换)会恢复原来的结构(因为交换两次相当于没有交换)。所以最后输出的两次交换后的遍历序列中,第二次交换后应该和最初的一样。但是,注意目最后要求输出的是二叉树的深度和叶子结点数,应该是在删除结点后的树(未进行交换)的状态下计算。然而,仔细看输出格式:第十九行:二叉树的深度第二十行:叶子结点数根据输出步骤,在第二次交换后(也就是第十六行到第十八行)之后输出深度和叶子数。但第二次交换后,树恢复到了删除结点后的状态(因为之前有两次交换,第一次交换后树被镜像,第二次交换又恢复)。所以实际上此时树就是删除结点后的树。因此,我们可以在第二次交换后(也就是在删除结点后的树的基础上进行了两次交换,因此树恢复原状)直接计算深度和叶子数,但注意:第一次交换是在删除结点之后,交换操作是在删除后的树上进行的。所以第二次交换后,树的结构和删除后的树是一样的(因为两次交换恢复),所以此时计算深度和叶子数其实就是删除结点后的树的深度和叶子数。但是,输出格式中,在第二次交换之后才输出深度和叶子数,所以我们在第二次交换后(此时树已经恢复成删除后的树)计算这些值。然而,这里有一个问:我们是否需要在删除后先不交换,先计算深度和叶子数?但是目要求在第二次交换后才输出深度和叶子数。不过,交换操作并不改变深度和叶子数(因为交换左右子树并不会改变树的结构,但是会改变遍历顺序,但深度不变,叶子节点数也不变)。所以实际上深度和叶子数在删除后就已经确定了,不受交换影响(因为交换两次后还是原来的树)。但是注意:交换子树其实会改变树的结构(变成了镜像),但是深度和叶子结点数量保持不变。所以我们可以这样:删除结点后,我们记这棵树为T。第一次交换:T1=swap(T)——T1是T的镜像,深度和叶子数T相同。第二次交换:T2=swap(T1)——T2就是T,深度和叶子数T相同。所以在T2上计算深度和叶子数,其实就是在T上计算。因此我们在第二次交换后(此时树已经恢复为T)再进行计算。所以,程序流程如下:1.读取n和n个整数,构建AVL树。2.输出前序、中序、后序(递归)。3.读取两个待查找的关键字,分别输出查找结果(1或0)。4.读取待插入关键字,插入,输出插入后的前序、中序(递归)、后序(递归)、中序(非递归)、层次遍历。5.读取待删除关键字,删除该结点,然后输出删除后的中序(非递归)和层次遍历。6.第一次交换:交换所有结点的左右子树,然后输出交换后的前序、中序、后序(递归)。7.第二次交换:再次交换,然后输出交换后的前序、中序、后序(递归)。8.输出深度和叶子数(在第二次交换后,树已经恢复成删除后的树,所以计算删除后树的深度和叶子数)。注意:在删除结点后,我们的树已经变为删除后的树。然后我们进行两次交换,第二次交换后树恢复到删除后的树(因为两次交换抵消)。所以第8步的深度和叶子数就是删除后的树的深度和叶子数。但是,这里有一个问目要求输出的两次交换后的遍历序列中,第二次交换后应该是恢复成删除后的树,所以第二次交换后的遍历序列应该和删除后的树的遍历序列(没有交换过的一样)。所以我们需要在删除结点后先保存这棵树(作为T),然后进行交换操作,第一次交换得到镜像,然后输出镜像的遍历序列;再交换回来,得到原树(T),输出原树的遍历序列。这样输出的第二次交换后的遍历序列应该和删除后未交换的遍历序列是一样的。但是,我们并没有要求输出删除后的所有递归遍历,所以删除后的树在删除后只输出了非递归中序和层次遍历,然后进行了交换操作。所以第一次交换后的遍历序列是镜像的,而第二次交换后的遍历序列恢复原样。所以,我们按以下步骤:-删除结点后的树(称为T),我们暂时不输出递归遍历,只输出非递归中序和层次遍历。-然后我们进行第一次交换(得到T_mirror),然后输出T_mirror的三种递归遍历。-然后我们进行第二次交换(得到T,即原删除后的树),然后输出T的三种递归遍历(应该和删除后不交换的递归遍历一致,但目没有要求删除后的递归遍历,所以我们只需要按照交换操作后的树输出即可)。-然后计算深度和叶子数(此时是T)。然而,目要求输出的最后两行是深度和叶子数,所以我们在最后输出。但是,我们需要注意的是,在删除结点后,树就已经变成了删除后的树,然后我们进行两次交换操作,第二次交换后树恢复成删除后的树(即T),所以我们在第二次交换操作后,输出深度和叶子数。因此,代码流程:步骤1:构建初始AVL树(root)。步骤2:输出初始的三种递归遍历。步骤3:输出两个查找结果。步骤4:插入新节点,然后输出插入后的递归遍历(前中后),再输出非递归中序和层次遍历。步骤5:删除节点(第六行输入的关键字),然后输出删除后的非递归中序遍历和层次遍历。步骤6:第一次交换,然后输出第一次交换后的前序、中序、后序遍历序列。步骤7:第二次交换(恢复),然后输出第二次交换后的前序、中序、后序遍历序列(即删除节点后未交换的树)。步骤8:输出深度和叶子数。但是这里有一个问:在删除节点后,我们输出的非递归中序和层次遍历是删除后未交换的树(T)的结果。而第一次交换后,我们得到镜像树,所以遍历序列会变。第二次交换后,我们又恢复成T。注意:交换两次后,树恢复原状,所以第二次交换后的遍历序列应该和删除后未交换的树的遍历序列一样(也就是和步骤5中我们输出的非递归中序和层次遍历的前序、中序、后序递归遍历版本一致吗?)但是步骤5中我们只输出了非递归中序和层次遍历,没有输出递归的三序遍历,所以这里我们按照要求输出两次交换后的递归三序遍历。因此,在步骤7中,我们输出第二次交换后的前序、中序、后序递归遍历,也就是删除节点后的树的递归三序遍历。所以,整个流程就符合目要求了。我们开始实现代码:注意:非递归后序遍历较为复杂,我们采用一个栈和一个指针指向前一个访问的结点来实现。另外,删除操作中,如果需要删除的结点有两个子结点,我们使用右子树的最小值结点来替代被删除结点。由于目要求严格,我们必须保证输出格式正确。下面我们写代码。</think> 以下是一个完整的平衡二叉排序树(AVL树)实现,满足所有要求的操作和输出格式: ```cpp #include <iostream> #include <vector> #include <queue> #include <stack> #include <algorithm> using namespace std; struct TreeNode { int val; int height; // 节点高度,用于平衡因子计算 TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), height(1), left(nullptr), right(nullptr) {} }; // 获取节点高度 int getHeight(TreeNode* node) { return node ? node->height : 0; } // 更新节点高度 void updateHeight(TreeNode* node) { node->height = max(getHeight(node->left), getHeight(node->right)) + 1; } // 计算平衡因子 int getBalanceFactor(TreeNode* node) { return getHeight(node->left) - getHeight(node->right); } // 右旋操作 TreeNode* rightRotate(TreeNode* y) { TreeNode* x = y->left; TreeNode* T = x->right; x->right = y; y->left = T; updateHeight(y); updateHeight(x); return x; } // 左旋操作 TreeNode* leftRotate(TreeNode* x) { TreeNode* y = x->right; TreeNode* T = y->left; y->left = x; x->right = T; updateHeight(x); updateHeight(y); return y; } // 平衡二叉树插入 TreeNode* insert(TreeNode* root, int key) { if (!root) return new TreeNode(key); if (key < root->val) { root->left = insert(root->left, key); } else if (key > root->val) { root->right = insert(root->right, key); } else { return root; // 重复值不插入 } updateHeight(root); int balance = getBalanceFactor(root); // 左左情况 if (balance > 1 && key < root->left->val) { return rightRotate(root); } // 右右情况 if (balance < -1 && key > root->right->val) { return leftRotate(root); } // 左右情况 if (balance > 1 && key > root->left->val) { root->left = leftRotate(root->left); return rightRotate(root); } // 右左情况 if (balance < -1 && key < root->right->val) { root->right = rightRotate(root->right); return leftRotate(root); } return root; } // 找到最小值节点(后继) TreeNode* minValueNode(TreeNode* node) { TreeNode* current = node; while (current && current->left) current = current->left; return current; } // 平衡删除节点 TreeNode* deleteNode(TreeNode* root, int key) { if (!root) return root; if (key < root->val) { root->left = deleteNode(root->left, key); } else if (key > root->val) { root->right = deleteNode(root->right, key); } else { if (!root->left || !root->right) { TreeNode* temp = root->left ? root->left : root->right; delete root; return temp; } else { TreeNode* temp = minValueNode(root->right); root->val = temp->val; root->right = deleteNode(root->right, temp->val); } } if (!root) return root; // 删除后为空 updateHeight(root); int balance = getBalanceFactor(root); // 左左情况 if (balance > 1 && getBalanceFactor(root->left) >= 0) { return rightRotate(root); } // 左右情况 if (balance > 1 && getBalanceFactor(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // 右右情况 if (balance < -1 && getBalanceFactor(root->right) <= 0) { return leftRotate(root); } // 右左情况 if (balance < -1 && getBalanceFactor(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root; } // 递归先序遍历 vector<int> preorderRecursive(TreeNode* root) { vector<int> res; if (root) { res.push_back(root->val); vector<int> left = preorderRecursive(root->left); vector<int> right = preorderRecursive(root->right); res.insert(res.end(), left.begin(), left.end()); res.insert(res.end(), right.begin(), right.end()); } return res; } // 非递归先序遍历 vector<int> preorderIterative(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> st; st.push(root); while (!st.empty()) { TreeNode* node = st.top(); st.pop(); res.push_back(node->val); if (node->right) st.push(node->right); if (node->left) st.push(node->left); } return res; } // 递归中序遍历 vector<int> inorderRecursive(TreeNode* root) { vector<int> res; if (root) { vector<int> left = inorderRecursive(root->left); res.insert(res.end(), left.begin(), left.end()); res.push_back(root->val); vector<int> right = inorderRecursive(root->right); res.insert(res.end(), right.begin(), right.end()); } return res; } // 非递归中序遍历 vector<int> inorderIterative(TreeNode* root) { vector<int> res; stack<TreeNode*> st; TreeNode* curr = root; while (curr || !st.empty()) { while (curr) { st.push(curr); curr = curr->left; } curr = st.top(); st.pop(); res.push_back(curr->val); curr = curr->right; } return res; } // 递归后序遍历 vector<int> postorderRecursive(TreeNode* root) { vector<int> res; if (root) { vector<int> left = postorderRecursive(root->left); vector<int> right = postorderRecursive(root->right); res.insert(res.end(), left.begin(), left.end()); res.insert(res.end(), right.begin(), right.end()); res.push_back(root->val); } return res; } // 非递归后序遍历 vector<int> postorderIterative(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> st; TreeNode* lastVisited = nullptr; TreeNode* curr = root; while (!st.empty() || curr) { if (curr) { st.push(curr); curr = curr->left; } else { TreeNode* top = st.top(); if (top->right && lastVisited != top->right) { curr = top->right; } else { res.push_back(top->val); lastVisited = top; st.pop(); } } } return res; } // 层次遍历 vector<int> levelOrder(TreeNode* root) { vector<int> res; if (!root) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* node = q.front(); q.pop(); res.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } return res; } // 查找节点 int search(TreeNode* root, int key) { TreeNode* curr = root; while (curr) { if (key == curr->val) return 1; curr = (key < curr->val) ? curr->left : curr->right; } return 0; } // 交换子树 TreeNode* swapTree(TreeNode* root) { if (!root) return nullptr; swap(root->left, root->right); swapTree(root->left); swapTree(root->right); return root; } // 计算树深度 int depth(TreeNode* root) { return root ? 1 + max(depth(root->left), depth(root->right)) : 0; } // 计算叶子节点数 int leafCount(TreeNode* root) { if (!root) return 0; if (!root->left && !root->right) return 1; return leafCount(root->left) + leafCount(root->right); } // 打印vector内容 void printVector(const vector<int>& v) { for (int i = 0; i < v.size(); i++) { if (i > 0) cout << " "; cout << v[i]; } cout << endl; } int main() { int n; cin >> n; vector<int> keys(n); for (int i = 0; i < n; i++) { cin >> keys[i]; } int target1, target2, insertKey, deleteKey; cin >> target1 >> target2 >> insertKey >> deleteKey; // 构建初始AVL树 TreeNode* root = nullptr; for (int key : keys) { root = insert(root, key); } // 1-3行:初始遍历序列(前序、中序、后序) printVector(preorderRecursive(root)); printVector(inorderRecursive(root)); printVector(postorderRecursive(root)); // 4-5行:查找结果 cout << search(root, target1) << endl; cout << search(root, target2) << endl; // 6-8行:插入新节点后的遍历序列 root = insert(root, insertKey); printVector(preorderRecursive(root)); printVector(inorderRecursive(root)); printVector(postorderRecursive(root)); // 9行:插入后的非递归中序 printVector(inorderIterative(root)); // 10行:插入后的层次遍历 printVector(levelOrder(root)); // 11行:删除后的非递归中序 root = deleteNode(root, deleteKey); printVector(inorderIterative(root)); // 12行:删除后的层次遍历 printVector(levelOrder(root)); // 13-15行:第一次交换后的遍历序列 root = swapTree(root); printVector(preorderRecursive(root)); printVector(inorderRecursive(root)); printVector(postorderRecursive(root)); // 16-18行:第二次交换后的遍历序列(恢复原树) root = swapTree(root); printVector(preorderRecursive(root)); printVector(inorderRecursive(root)); printVector(postorderRecursive(root)); // 19行:树的深度 cout << depth(root) << endl; // 20行:叶子节点数 cout << leafCount(root) << endl; return 0; } ``` ### 算法详解 1. **AVL树平衡机制**: - 使用高度平衡因子维护平衡 - 实现4种旋转操作:左旋、右旋、左右旋、右左旋 - 插入和删除时自动调整平衡 2. **遍历算法实现**: - 递归遍历:直接按遍历顺序递归处理子树 - 非递归遍历: - 前序:使用栈,按根->右->左顺序入栈 - 中序:使用栈模拟递归调用顺序 - 后序:使用辅助指针标记最后访问节点 3. **特殊操作**: - 交换子树:递归交换所有节点的左右子树 - 深度计算:递归计算左右子树最大深度 - 叶子计数:递归统计无子节点的节点数 - 删除节点:处理三种情况(无子、单子、双子节点) 4. **主要函数说明**: - `insert()`:平衡插入,保持AVL树特性 - `deleteNode()`:平衡删除,考虑多种情况 - `search()`:基于BST特性高效查找 - `levelOrder()`:BFS实现层次遍历
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值