关闭

数据结构-二叉树遍历

27人阅读 评论(0) 收藏 举报
import java.util.Stack;
/*
 * 用递归和非递归实现二叉树的前序,中序。后序遍历
 * */
public class Problem1 {
	/*递归实现*/
	public static void preOrderTraverse(BNode root){
		if(root == null) return;
		System.out.print(root.value + " ");
		preOrderTraverse(root.left);
		preOrderTraverse(root.right);
	}

	public static void inOrderTraverse(BNode root){
		if(root == null) return;
		inOrderTraverse(root.left);
		System.out.print(root.value + " ");
		inOrderTraverse(root.right);
	}
	
	public static void postOrderTraverse(BNode root){
		if(root == null) return;
		postOrderTraverse(root.left);
		postOrderTraverse(root.right);
		System.out.print(root.value + " ");
	}
	/*非递归实现*/
	public static void preOrderTraverse1(BNode root){
		if(root == null) return;
		Stack<BNode> stack = new Stack<BNode>();
		stack.add(root);
		while( !stack.isEmpty()){
			root = stack.pop();
			System.out.print(root.value + " ");
			if(root.right != null) stack.add(root.right);
			if(root.left != null) stack.add(root.left);
		}
		System.out.println();
	}
	
	public static void inOrderTraverse1(BNode root){
		if(root == null) return;
		Stack<BNode> stack = new Stack<BNode>();
		BNode cur = root;
		while(!stack.isEmpty() || cur != null){
			if(cur != null){
				stack.push(cur);
				cur = cur.left;
			}else{
				cur = stack.pop();
				System.out.print(cur.value+" ");
				cur = cur.right;
			}
		}
		System.out.println();
	}
	
	public static void postOrderTraverse1(BNode root){
		if(root == null) return;
		Stack<BNode> s1 = new Stack<BNode>();
		Stack<BNode> s2 = new Stack<BNode>();
		BNode cur = root;
		s1.add(cur);
		while(!s1.isEmpty()){
			cur = s1.pop();
			s2.add(cur);
			if(cur.left != null) s1.add(cur.left);
			if(cur.right != null) s1.add(cur.right);
		}
		while( !s2.isEmpty()){
			cur = s2.pop();
			System.out.print(cur.value + " ");
		}
		System.out.println();
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BNode n1 = new BNode(1);
		BNode n2 = new BNode(2);
		BNode n3 = new BNode(3);
		BNode n4 = new BNode(4);
		BNode n5 = new BNode(5);
		BNode n6 = new BNode(6);
		BNode n7 = new BNode(7);
		n1.left = n2;
		n1.right = n3;
		n2.left = n4;
		n2.right = n5;
		n3.left = n6;
		n3.right = n7;
		
		postOrderTraverse1(n1);
		postOrderTraverse(n1);

	}

}
public class BNode {
	public int value;
	public BNode left;
	public BNode right;
	public BNode(int valur){
		this.value = valur;
	}
	
	@Override
	public String toString() {
		return "BNode [value=" + value + ", left=" + left + ", right=" + right
				+ "]";
	}

}


0
0
猜你在找
【直播】计算机视觉原理及实战——屈教授
【套餐】深度学习入门视频课程——唐宇迪
【套餐】Hadoop生态系统零基础入门
【套餐】嵌入式Linux C编程基础
【套餐】2017软考系统集成项目——任铄
【套餐】Android 5.x顶级视频课程——李宁
【直播】广义线性模型及其应用——李科
【直播】从0到1 区块链的概念到实践
【直播】机器学习之凸优化——马博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:971次
    • 积分:142
    • 等级:
    • 排名:千里之外
    • 原创:13篇
    • 转载:5篇
    • 译文:0篇
    • 评论:0条
    文章存档