二叉树的非递归遍历

1、先序遍历
遍历顺序:根左右,利用栈

public void preOrder(TNode root){
	if(root==null){
		return ;
	}
	Stack<TNode> s=new Stack<TNode>();
	while(!s.empty()||root!=null){
		while(root!=null){
			print(root.val);
			s.push(root);
			root=root.left;
		}
		if(!s.empty()){
			root=s.pop();
			root=root.right;
		}
	}
}

2、中序遍历
遍历顺序:左根右,利用栈

public void inOrder(TNode root){
	if(root==null){
		return ;
	}
	Stack<TNode> s=new Stack<TNode>();
	while(!s.empty()||root!=null){
		while(root!=null){
			s.push(root);
			root=root.left;
		}
		if(!s.empty()){
			root=s.pop();
			print(root.val);
			root=root.right;
		}
	}
}

3、后序遍历
遍历顺序:左右根,利用栈,如果左右孩子都访问完了之后就访问根节点,否则将右孩子、左孩子压栈。那么如何判断左右孩子都访问过了呢?可以设一个变量last保存上一次访问的节点.

public void postOrder(TNode root){
	if(root==null){
		return ;
	}
	Stack<TNode> s=new Stack<TNode>();
	s.push(root);
	TNode last=root;
	TNode p;
	while(!s.empty()){
		p=s.top();
		if((root.left==null&&root.right==null)||(root.right==null&&last==root.left)||(last==root.right)){//左右孩子节点都访问完了
			print(root.val);
			last=p;
			s.pop();
		}else{
			if(p.right)
				s.push(p.right);
			if(p.left)
				s.push(p.left);
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值