二叉树先中后序遍历(递归和非递归版本)

16 篇文章 0 订阅

先序:

public void preOrder(TreeNode root) {
if(root == null){
return ;
}
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur=stack.pop();
System.out.print(cur.val);
if(cur.right != null){
stack.push(cur.right);
}
if(root.left!= null){
stack.push(cur.left);
		}
	}
}

二叉树的中序遍历

public void inOrder(TreeNode root) {
if(root == null){
return;}
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(true){
	while(cur!=null){
	stack.pop(cur);
	cur=cur.left;
	}
	if(stack.isEmpty()){
	break;
	}
	TreeNode top=stack.pop();
	System.out.print(top.val);
	cur=top.right;
	}
}

二叉树的后序遍历

public static void postOrder(TreeNode root) {
if(root == null){
return ;}
TreeNode cur=root;
TreeNode prev=null;
while(true){
	while(cur!=null){
	stack.pop(cur);
	cur=cur.left;
	}
	if(stack.isEmpty()){
	break;
	}
	TreeNode top=stack.peek();
	if(top.right == null || top.right=prev){
		System.out.print(top.val);
		stack.pop;
		prev=pop;
	}else{
	cur=top.right;
		}
	}
}

也就是说二叉树的三序遍历,都是通过特殊的数据结构——栈来实现。
至于为什么这样实现,有兴趣的同学可以接下来试试。

递归版本
先序:

public void preOrder(TreeNode root) {
if(root == null){
return ;
}
System.out.print(root.val);
preOrder(root.left);
preOrder(root.right);
}

中序:

public void inOrder(TreeNode root) {
if(root == null){
return ;
}
inOrder(root.left);
System.out.print(root.val);
inOrder(root.right);
}

后序:

public void postOrder(TreeNode root){
if(root == null){
return;}
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值