二叉树的三种非递归遍历及层序遍历

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

public class Traverse {

	public static void main(String[] args) {
		Node n1 = new Node(1);
		Node n2 = new Node(2);
		Node n3 = new Node(3);
		Node n4 = new Node(4);
		Node n5 = new Node(5);
		Node n6 = new Node(6);
		Node n7 = new Node(7);

		n1.left = n2;
		n1.right = n3;
		n2.left = n4;
		n2.right = n5;
		n3.left = n6;
		n3.right = n7;

		preOrder(n1);
		inOrder(n1);
		postOrder(n1);
		levelOrder(n1);
	}

	static void preOrder(Node head) {
		if (head == null) {
			return;
		}

		Stack<Node> stack = new Stack<>();
		stack.push(head);

		while (!stack.isEmpty()) {
			Node cur = stack.pop();
			System.out.print(cur.value + " ");

			// 因为先序遍历是“根左右”,先左后右,所以入栈的时候要先右后左的入,出栈时才能先左后有
			if (cur.right != null) {
				stack.push(cur.right);
			}

			if (cur.left != null) {
				stack.push(cur.left);
			}
		}

		System.out.println();
	}

	static void inOrder(Node head) {
		if (head == null) {
			return;
		}

		Stack<Node> stack = new Stack<>();
		Node cur = head;

		// 当cur不为空时,可能是左边节点要继续进栈;也可能是右边节点要进栈;所以还要继续处理,这时不能结束循环。
		// 当栈不空时,肯定还没处理完所有元素,这时也不能结束循环
		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();
	}

	static void postOrder(Node head) {
		if (head == null) {
			return;
		}

		Stack<Node> s1 = new Stack<>();
		Stack<Node> s2 = new Stack<>();

		s1.push(head);
		while (!s1.isEmpty()) {
			Node cur = s1.pop();
			s2.push(cur);
			if (cur.left != null) {
				s1.push(cur.left);
			}
			if (cur.right != null) {
				s1.push(cur.right);
			}
		}

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

		System.out.println();
	}

	static void levelOrder(Node head) {
		if (head == null) {
			return;
		}

		Queue<Node> queue = new LinkedList<>();
		// 根节点先入队
		queue.offer(head);

		// 当队列不空时,将队头元素出队的同时存入临时变量,并输出该节点的值
		while (queue.peek() != null) {
			Node temp = queue.poll();
			System.out.print(temp.value + " ");

			// 左节点先入队
			if (temp.left != null) {
				queue.offer(temp.left);
			}

			// 右节点后入队
			if (temp.right != null) {
				queue.offer(temp.right);
			}
		}

		System.out.println();
	}
}

class Node {
	int value;
	Node left;
	Node right;

	Node(int value) {
		this.value = value;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值