二叉树的非递归【前/中/后 序遍历】

本文介绍了一种使用栈来实现二叉树遍历的方法,包括前序、中序和后序遍历,并通过Java代码详细展示了算法的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

核心思想: 利用 存储需要反复遍历的节点!

import java.util.Stack;

class Node {
	int value;
	Node left;
	Node right;
	int signal;
	
	public Node() {}
	public Node(int value, Node left, Node right, int signal) {
		super();
		this.value = value;
		this.left = left;
		this.right = right;
		this.signal = signal;
	}
	
	
}

public class Main {

	public static void main(String[] args) {
		
		Node rleft = new Node(9,null,null,0);
		Node lright = new Node(7,null,null,0);

		Node left = new Node(3,null,lright,0);
		Node right = new Node(1,rleft,null,0);
		Node tree = new Node(4,left,right,0);
				
		PreOrder(tree);
		PostOrder(tree);
		InOrder(tree);
	}

	public static void InOrder(Node root) {
		
		if(root == null)
			return;
		if(root.left == null && root.right == null) {
			System.out.println(root.value);
			return;
		}
		Node tree = root;
		Stack<Node> st = new Stack<Node>();
		st.push(tree);
		
		while(!st.empty()) {
			while(tree.left != null) {
				st.push(tree.left);
				tree = tree.left;
			}
			Node tmp = st.pop();
			System.out.println(tmp.value);
			if(tmp.right != null) {
				st.push(tmp.right);
				tree = tmp.right;
			}
		}
	}
	
	public static void PostOrder(Node root) {
		
		if(root == null)
			return;
		if(root.left == null && root.right == null) {
			System.out.println(root.value);
			return;
		}
		
		Node tree = root;
		Stack<Node> st = new Stack<Node>();
		st.push(tree);
		
		while(!st.empty()) {
			Node tmp = st.lastElement();
			if(tmp.signal == 0) {
				if(tmp.left == null || tmp.left.signal == 2)
					tmp.signal = 1;
				else 
					st.push(tmp.left);
			}
			else if(tmp.signal == 1) {
				if(tmp.right == null || tmp.right.signal == 2)
					tmp.signal = 2;
				else 
					st.push(tmp.right);
			}
			else if (tmp.signal == 2) {
				System.out.println(tmp.value);
				st.pop();
				
			}
		}
	}
	
	
	
	public static void PreOrder(Node root) {
		Node tree = root;
		Stack<Node> st = new Stack<Node>();
		
		if(tree != null) 
			st.push(tree);
		
		while(!st.empty()) {
			Node tmp = st.pop();
			if(tmp.signal == 0) {
				System.out.println(tmp.value);
				tmp.signal = 1;
				
				if(tmp.left == null) {
					if(tmp.right != null) 
						st.push(tmp.right);
				}
				else {
					st.push(tmp);
					st.push(tmp.left);
				}
				
			}
			else {
				if(tmp.right != null)
					st.push(tmp.right);
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值