打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
二叉树遍历非递归算法

二叉树遍历的非递归算法(java实现)

package com.mpackage.tree;import java.util.*;public class TreeSolution {		//先根遍历	public static ArrayList<Integer> prePrint(TreeNode t){		ArrayList<Integer> result=new ArrayList<Integer>();		if(t==null){			return result;		}		Stack<TreeNode> stack=new Stack<TreeNode>();		while(!stack.isEmpty()||t!=null){			while(t!=null){				result.add(t.val);				stack.push(t);				t=t.left;			}			if(!stack.isEmpty()){				TreeNode tnode=stack.pop();				t=tnode.right;			}		}		return result;	}		//先序遍历2	public static ArrayList<Integer> prePrint2(TreeNode t){		ArrayList<Integer> list=new ArrayList<Integer>();		if(t==null){			return list;		}		Stack<TreeNode> stack=new Stack<TreeNode>();		stack.push(t);		TreeNode node;		while(!stack.isEmpty()){			node=stack.pop();			list.add(node.val);			if(node.right!=null){				stack.push(node.right);			}			if(node.left!=null){				stack.push(node.left);			}		}		return list;	}		//中序遍历	public static ArrayList<Integer> midPrint(TreeNode t){		ArrayList<Integer> result=new ArrayList<Integer>();		if(t==null){			return result;		}		Stack<TreeNode> stack=new Stack<TreeNode>();		while(!stack.isEmpty()||t!=null){			while(t!=null){				stack.push(t);				t=t.left;			}			if(!stack.isEmpty()){				TreeNode tnode=stack.pop();				result.add(tnode.val);				t=tnode.right;			}		}		return result;	}		//后序遍历	public static ArrayList<Integer> postPrint(TreeNode t){		ArrayList<Integer> list=new ArrayList<Integer>();		if(t==null){			return list;		}		TreeNode node=null;		TreeNode pre=null;//上一个访问的节点		Stack<TreeNode> stack=new Stack<TreeNode>();		while(t!=null||!stack.isEmpty()){			while(t!=null){				stack.push(t);				t=t.left;			}			if(!stack.isEmpty()){				node=stack.peek();				//如果该节点的右孩子为空或者等于上一个访问的节点,则可以访问该节点				if(node.right!=null&&node.right!=pre){					t=node.right;				}				else{					stack.pop();					list.add(node.val);					pre=node;				}			}		}		return list;	}		//后序遍历2	//思路:后序遍历顺序为左->右->根,	//可以按根->右->左遍历,然后转置;	public static ArrayList<Integer> postPrint2(TreeNode t){		ArrayList<Integer> list=new ArrayList<Integer>();		if(t==null){			return list;		}		Stack<TreeNode> stack=new Stack<TreeNode>();		stack.push(t);		TreeNode node=null;		while(!stack.isEmpty()){			node=stack.pop();			list.add(node.val);			if(node.left!=null){				stack.push(node.left);			}			if(node.right!=null){				stack.push(node.right);			}		}		Collections.reverse(list);		return list;	}	}
来源:http://www.icode9.com/content-1-37951.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
二叉树先序中序后序三种遍历的非递归算法|二叉树,先序,中序,后序遍历,非递归算法-中国源码...
泄题了?Java程序员最可能被考到的面试题,命中率极高!
算法和编程面试题精选TOP50!(附代码 解题思路 答案)
630页!熬夜整理出的''高分宝典'':算法 数据结构 网络 操作系统
【小Y学算法】⚡️每日LeetCode打卡⚡️——25.二叉树的中序遍历
算法2(递归和非递归俩种方法实现二叉树的前序遍历)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服