二叉树前序遍历,中序遍历非递归版本

#include<iostream>
#include<stack>
using namespace std;
struct node{  
    int data;  
    node *left;  
    node *right;  
    node(int value):data(value),left(NULL),right(NULL){}  
}; 
/*void preorder(node *root){
	stack<node*> s;
	node *p=root;
	while(p!=NULL||!s.empty()){
		while(p!=NULL){
			cout<<p->value<<" ";
			s.push(p);
			p=p->left;
		}
		if(!s.empty()){
			p=s.top();
			s.pop();
			p=p->right;
		}
	}
}*/
void preorder(node *root){
	stack<node*> s;
	node *p=root;
	if(p==NULL)return;
	//push the left tree into stack
	while(p!=NULL){
		cout<<p->data;
		s.push(p);
		p=p->left;
	}
	//traverse the left then goto the right subtree
	while(!s.empty()){
		p=s.top();
		s.pop();
		p=p->right;
		//push the left subtree
		while(p!=NULL){
			cout<<p->data;
			s.push(p);
			p=p->left;
		}
	}
}
int main(){
	node p1(1);  
    node p2(2);  
    node p3(3);  
    node p4(4);  
    node p5(5);  
    node p6(6);  
    p1.left=&p2;  
    p1.right=&p3;  
    p2.right=&p4;  
    p4.right=&p5;  
    preorder(&p1); 
    return 0;



}

前序遍历(Preorder traversal):根->左子树->右子树。用栈来存储节点,沿着根节点一直往左子树走,该路径上的节点依次输出并压入栈中直到左子树为空,然后取栈顶元素,遍历每个栈中元素的右子树部分。前序遍历即深度优先搜索(DFS)。





中序遍历:用栈来存储节点,因为前序遍历是先左子树->根节点->右子树。因此先沿着根节点找最左边的节点,依次压栈,出栈的时候,因为栈这时没有节点的右子树信息。若

某个节点存在右子树,则压入右子树中的节点。先压入右子树的根节点。在该右子树上,对右子树根节点到右子树最左边节点的路径上的节点依次压栈

#include<iostream>
#include<stack>
using namespace std;
struct node{
	int data;
	node *left;
	node *right;
	node(int value):data(value),left(NULL),right(NULL){}
};

void Inorder(node *p){
	stack<node*> s;
	if(p==NULL)return;
	node *cur=p;
	//last node being visted
	node *last;
	//goto the left-most node
	while(cur!=NULL){
		s.push(cur);
		cur=cur->left;
	}
	while(!s.empty()){
		last=s.top();
		s.pop();
		cout<<last->data<<" ";
		//consider the right child 
		//of each node
		if(last->right!=NULL){
			cur=last->right;
			while(cur!=NULL){
				s.push(cur);
				cur=cur->left;
			}
		}


	}
}
int main(){
	node p1(1);
	node p2(2);
	node p3(3);
	node p4(4);
	node p5(5);
	node p6(6);
	p1.left=&p2;
	p1.right=&p3;
	p2.right=&p4;
	p4.right=&p5;
	Inorder(&p1);
	
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值