【数据结构·考研】中序遍历二叉树

中序遍历二叉树

中序遍历二叉树的非递归实现:

先不停往左孩子方向走,一边往左走一边入栈,等走到尽头后输出一个结点来访问,然后走向这个结点的右孩子。在右孩子结点非空或栈非空的状态下,不停迭代上述过程。

依旧是这棵老树:

/*------------
树的形状:
      a
    b   c
  d  e f 
--------------*/

代码如下:

#include<iostream>
#include<stack>
#include<queue>
using namespace std; 

typedef struct node{
	char val;
	struct node* left;
	struct node* right;
}TreeNode,*Tree;

//中序遍历(递归) 
void InOrder(Tree& t){
	if(t == NULL) return;
	//递归遍历左子树
	InOrder(t->left);
	cout<<t->val<<" ";//输出当前结点的值   
	//递归遍历右子树
	InOrder(t->right);  
} 

//中序遍历(非递归) 
void InOrderTraversal(Tree& t){
	stack<TreeNode*> s; //创建一个树结点型的栈
	TreeNode* p = t; 
	while(p != NULL || !s.empty()){
		//左孩子不为空,一直往左走 
		while(p != NULL){
			s.push(p);
			p=p->left;
		}
		//出栈访问 
		p = s.top();
		cout<<p->val<<" ";
		s.pop();
		//走向右孩子 
		p = p->right; 
	}
}

void CreateTree(Tree& t){
	char x;
	cin>>x;
	if(x == '#') t = NULL; 
	else{
		t = new TreeNode; 
		t->val = x;  
		CreateTree(t->left); 
		CreateTree(t->right); 
	}
} 

void levelOrder(Tree& t) {
    if(t == NULL) return;
    queue<TreeNode*> q;
    q.push(t);
    while(!q.empty()){
        int n = q.size();
        for(int i = 0;i<n;i++){
            TreeNode* s = q.front();
            cout<<s->val<<" ";
            q.pop();
            if(s->left) q.push(s->left);
            if(s->right) q.push(s->right);
        }
        cout<<endl;
    } 
}

int main(){
	Tree t;
	CreateTree(t);
	/*
	   a b d # # e # # c f # # #
	*/
	levelOrder(t); 
	cout<<endl<<"递归:"<<endl;
	InOrder(t);
	cout<<endl<<"非递归:"<<endl;
	InOrderTraversal(t);	
}

运行结果:

猜你喜欢

转载自blog.csdn.net/cjw838982809/article/details/108227073