遍历二叉树

 

package com.example.demo.test;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class Order {

	static class Tree {
		int value;
		Tree left;
		Tree right;

		public Tree(int value, Tree t1, Tree t2) {
			this.value = value;
			this.left = t1;
			this.right = t2;
		}

	}

	public static Tree init() {
		Tree J = new Tree(8, null, null);
		Tree H = new Tree(4, null, null);
		Tree G = new Tree(2, null, null);
		Tree F = new Tree(7, null, J);
		Tree E = new Tree(5, H, null);
		Tree D = new Tree(1, null, G);
		Tree C = new Tree(9, F, null);
		Tree B = new Tree(3, D, E);
		Tree A = new Tree(6, B, C);
		return A; // 返回根节点
	}

	// 前序遍历
	public static void preOrder(Tree tree) {
		if (tree == null) {
			return;
		}
		Stack<Tree> stack = new Stack();
		Tree node = tree;
		while (null != node || !stack.isEmpty()) {
			if (null != node) {
				System.out.print(node.value + " ");
				stack.push(node);
				node = node.left;
			} else {
				node = stack.pop().right;
			}
		}
	}

	// 中序遍历
	public static void inOrder(Tree tree) {
		if (tree == null) {
			return;
		}
		Stack<Tree> stack = new Stack();
		Tree node = tree;
		while (null != node || !stack.isEmpty()) {
			if (null != node) {
				stack.push(node);
				node = node.left;
			} else {
				node = stack.pop();
				System.out.print(node.value + " ");
				node = node.right;
			}
		}
	}

	// 后序遍历
	public static void lastOrder(Tree tree) {
		if (tree == null) {
			return;
		}
		Stack<Tree> stack = new Stack<Tree>();
		Stack<Tree> outStack = new Stack<Tree>();
		Tree node = tree;
		while (null != node || !stack.isEmpty()) {
			if (null != node) {
				outStack.push(node);
				stack.push(node);
				node = node.right;
			} else {
				node = stack.pop();
				node = node.left;
			}

		}
		while (!outStack.isEmpty()) {
			System.out.print(outStack.pop().value + " ");
		}
	}

	// 深度遍历
	public static void deepOrder(Tree tree) {
		if (tree == null) {
			return;
		}
		Queue<Tree> queue = new LinkedList<Tree>();
		queue.add(tree);

		while (!queue.isEmpty()) {
			Tree node = queue.poll();
			System.out.print(node.value + " ");
			if (node.left != null) {
				queue.add(node.left);
			}
			if (node.right != null) {
				queue.add(node.right);
			}
		}
	}

	// 递归方式(前序)
	public static void order(Tree tree) {
		if (tree != null) {
			System.out.print(tree.value + " ");
			order(tree.left);
			order(tree.right);
		}

	}

	public static void main(String[] args) {
		preOrder(Order.init());
		order(Order.init());
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值