二叉树学习总结-建立、广度优先算法,前序中序后序非递归算法

二叉树的知识前后学习过几遍,学习过后过段时间总是会遗忘,记录下这次的学习内容,权当做笔记了。也欢迎大家批评指正,共同进步。

树节点定义:

 

struct treenode
{
	int data;
	treenode *lchild;
	treenode *rchild;
};
指向树的结构:

struct tree
{
treenode *root;
};
 

 

一、树的建立

树的建立用的是插入结点的算法:将待插入的结点表示为tempptr,将这个结点值从树根开始向下进行比较:若大于一个比较结点tempptr1则转向比较的右子女,否则转向左子女,直到比较的结点tempptr1为空。在比较的过程中需要一个辅助指针pretempptr1,作为比较结点tempptr1的父结点。最后将tempptr作为pretempptr1的子女,当然还要判断是做左子女还是做右子女。

 

void maketree(treenode *&root)
{
	int temp;
	treenode *pretempptr1,*tempptr1;
	cout<<"please input a number:\n";
	cin>>temp;
	if(temp==-1)   //若输入-1表示结束树的输入
	{
		root=NULL;
		return;
	}
	treenode *tempptr=new treenode;
	tempptr->data=temp;
	tempptr->lchild=NULL;
	tempptr->rchild=NULL;

	root=tempptr;
	
	cout<<"please input a number:\n";
	cin>>temp;
	while(temp!=-1)
	{
		pretempptr1=root;
		tempptr1=root;

		tempptr=new treenode;
		tempptr->data=temp;
		tempptr->lchild=NULL;
		tempptr->rchild=NULL;


		while(tempptr1!=NULL)
		{
			pretempptr1=tempptr1;
			if(tempptr1->data>tempptr->data)
				tempptr1=tempptr1->lchild;
			else
				tempptr1=tempptr1->rchild;
		}
		if(pretempptr1->data>tempptr->data)
		{
			pretempptr1->lchild=tempptr;
		}
		else
			pretempptr1->rchild=tempptr;
		cout<<"please input a number:\n";
	    cin>>temp;
	}
}


二、广度优先算法

广度优先算法,采用自上而下,从左到右的顺序来遍历。遍历借助队列来实现,实现的要点为:每访问一个结点,若此结点的左子女非空,则将此左子女加入队列;若右子女非空,则将此右子女加入队列。通过这种方式即可保证每一层的结点自左到右依次加入队列。

 

void breadfirst(treenode *&root)
{
	queue<treenode *> queue_tree;
	treenode *temp=root;
	if(root==NULL)
	{
		cout<<"the tree is empty!"<<endl;
		return;
	}
	queue_tree.push(temp);
	while(!queue_tree.empty())
	{
		temp=queue_tree.front();
		queue_tree.pop();
		cout<<temp->data<<" ";
		if(temp->lchild!=NULL)
			queue_tree.push(temp->lchild);
		if(temp->rchild!=NULL)
			queue_tree.push(temp->rchild);
	}
}

 

三、树的非递归遍历

 

前序:

void iterativeNLR(treenode *&root)
{
	stack<treenode *> stack_tree;
	treenode *temp;
	if(root==NULL)
	{
		cout<<"the tree is empty!"<<endl;
		return;
	}
	temp=root;
	//stack_tree.push(root);
	while(temp!=NULL||!stack_tree.empty())
	{
		while(temp!=NULL)
		{
			cout<<temp->data<<" ";
			stack_tree.push(temp);
			temp=temp->lchild;
		}
		if(!stack_tree.empty())
		{
			temp=stack_tree.top();
			stack_tree.pop();
			temp=temp->rchild;
		}
	}
}

中序:

void iterativeLNR( treenode *&root)
{
	stack<treenode *> stack_tree;
	treenode *temp;
	if(root==NULL)
	{
		cout<<"the tree is empty!"<<endl;
		return;
	}
	temp=root;
	//stack_tree.push(temp);
	
	while(!stack_tree.empty()||temp!=NULL)
	{
		while(temp!=NULL)
		{
			stack_tree.push(temp);
			temp=temp->lchild;
		}
		
		if(!stack_tree.empty())
		{
		    temp=stack_tree.top();
		    cout<<temp->data<<" ";
		    stack_tree.pop();
		  //  if(temp->rchild!=NULL)
			   temp=temp->rchild;
		}
	}
}

后序:

后序稍微复杂一些,因为在访问完一个左子女后待访问该结点的父结点时,需要判断该父结点的右子女是否已经访问:可以借助于一个bool型变量来实现。当bool=true时表示右子女已经访问。

void iterativeLRN(treenode *&root)
{
	stack<pair<treenode *,bool>> stack_tree;
	treenode *temp=root;
	if(root==NULL)
	{
		cout<<"the tree is empty!"<<endl;
		return;
	}
	while(temp!=NULL||!stack_tree.empty())
	{
		while(temp!=NULL)
		{
			stack_tree.push(make_pair(temp,false));
			temp=temp->lchild;
		}

		if(!stack_tree.empty()&&stack_tree.top().second==true)
		{
			cout<<stack_tree.top().first->data<<" ";
			stack_tree.pop();
		}
		if(!stack_tree.empty())
		{
			stack_tree.top().second=true;
			temp=stack_tree.top().first->rchild;
		}
	}
}

2018.12.30 上述后序非递归方法保存所有的节点状态,耗费内存,可以进行优化:遍历到当前节点时,只保留下当前节点的遍历状态即可。代码如下:

vector<int> postOrder(TreeNode *root)
{
    vector<int> res;
    if(root == NULL) return res;

    TreeNode *p = root;
    stack<TreeNode *> sta;
    TreeNode *last = root;
    sta.push(p);
    while (!sta.empty())
    {
        p = sta.top();
        if( (p->left == NULL && p->right == NULL) || (p->right == NULL && last == p->left) || (last == p->right) )
        {
            res.push_back(p->val);
            last = p;
            sta.pop();
        }
        else 
        {
            if(p->right)
                sta.push(p->right);
            if(p->left)
                sta.push(p->left);
        }

    }


    return res;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
#include #include //#define error 0 //#define OVERFLOW -1 //#define ok 1 #define MAXSIZE 100 typedef char TElemType; typedef int Status; typedef struct BiTNode{ //树的结点 TElemType data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; typedef BiTree datatype; typedef struct { datatype data[MAXSIZE]; int top; }sqstack; typedef sqstack *STK; Status CreateBiTree(BiTree *T) { //先序建立二叉树 char ch; ch=getchar(); if(ch=='#') (*T)=NULL; //#代表空 else { (*T)=(BiTree)malloc(sizeof(BiTNode)); (*T)->data=ch; CreateBiTree(&(*T)->lchild); //先序建立左子树 CreateBiTree(&(*T)->rchild); //先序建立右子树 } return 1; } STK initstack() //栈的初始化 { STK s; s=(STK)malloc(MAXSIZE*sizeof(sqstack)); s->top=0; return s; //返回指向栈地址的指针 } Status stackempty(STK s) //判断栈是否为空 { return(s->top==0); } Status push(STK s,datatype *e) //压栈函数 { if(s->top==MAXSIZE) //栈满,则返回错误 return 0; else { s->data[s->top]=*e; (s->top)++; return 1; } } Status pop(STK s,datatype *e) //出栈函数 { if(stackempty(s)) //判断栈是否为空 return 0; else { s->top--; *e=s->data[s->top]; //用e接受栈顶元素 return 1; } } Status inordertraverse(BiTree T) //中序非递归遍历二叉树 { STK s; s=initstack(); // BiTree T; BiTree p; p=T; while (p||!stackempty(s)) { if(p) { push(s,&p); p=p->lchild; } else { pop(s,&p); printf("%2c",p->data); p=p->rchild; }//else }//while return 1; }//inordertraverse void main() { BiTree T=NULL; printf("\n Creat a Binary Tree .\n"); //建立一棵二叉树T* CreateBiTree( &T ); printf ("\nThe preorder is:\n"); inordertraverse(T); }
当然,二叉树遍历有三种主要方式:先序遍历(根-左-右)、中序遍历(左-根-右)和后序遍历(左-右-根)。非递归的层次遍历(也叫广度优先遍历,从上到下、从左到右)通常使用队列来辅助实现。 这里分别给出这些遍历非递归算法代码: 1. 层序遍历广度优先遍历): ```c #include <stdio.h> #include <stdlib.h> #include <queue> struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; void levelOrder(struct TreeNode* root) { if (root == NULL) return; // 使用队列存储每一层的节点 queue<struct TreeNode*> q; q.push(root); while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; i++) { struct TreeNode* node = q.front(); q.pop(); printf("%d ", node->val); // 打印当前节点值 if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); } printf("\n"); // 换行表示新的一层 } } ``` 2. 先序遍历(递归和非递归两种方式,这里是非递归版本,使用栈): ```c void preorderNonRecursive(struct TreeNode* root) { if (root == NULL) return; stack<struct TreeNode*> s; s.push(root); while (!s.empty()) { struct TreeNode* node = s.top(); s.pop(); printf("%d ", node->val); // 打印当前节点值 if (node->right != NULL) s.push(node->right); if (node->left != NULL) s.push(node->left); } } ``` 3. 中序遍历非递归,同样使用栈): ```c void inorderNonRecursive(struct TreeNode* root) { if (root == NULL) return; stack<struct TreeNode*> s; struct TreeNode* curr = root; while (curr != NULL || !s.empty()) { while (curr != NULL) { s.push(curr); curr = curr->left; } curr = s.top(); s.pop(); printf("%d ", curr->val); // 打印当前节点值 curr = curr->right; } } ``` 4. 后序遍历非递归,使用两个栈): ```c void postorderNonRecursive(struct TreeNode* root) { if (root == NULL) return; stack<struct TreeNode*> s1, s2; s1.push(root); while (!s1.empty()) { struct TreeNode* node = s1.top(); s1.pop(); s2.push(node); if (node->left != NULL) s1.push(node->left); if (node->right != NULL) s1.push(node->right); } while (!s2.empty()) { struct TreeNode* node = s2.top(); s2.pop(); printf("%d ", node->val); // 打印当前节点值 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值