二叉树的遍历

博客主要介绍了两种方式,分别是递归方式和非递归方式,未提及更多详细信息。

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

一、递归方式

//先序遍历
public static void preOrderRecur(Node root) {
		if (root == null) {
			return;
		}
		System.out.print(root.value+ " ");
		preOrderRecur(root.left);
		preOrderRecur(root.right);
		
	}
	
//中序遍历	
public static void inOrderRecur(Node root) {
		if (root == null) {
			return;
		}
		inOrderRecur(root.left);
		System.out.print(root.value+ " ");
		inOrderRecur(root.right);
		
	}
	
//后序遍历
public static void posOrderRecur(Node root) {
		if (root == null) {
			return;
		}
		posOrderRecur(root.left);
		posOrderRecur(root.right);
		System.out.print(root.value+ " ");
		
	}

二、非递归方式

//先序遍历
public static void preOrderUnRecur(Node root) {
		if (root == null) {
			return;
		}
		Stack<Node> stack = new Stack<>();
		while ((root !=null) || (!stack.isEmpty())) {
			while (root != null) {
				stack.push(root);
				System.out.print(root.value + " ");
				root = root.left;
			}
			if (!stack.isEmpty()) {
				root = stack.pop();
				
				root = root.right;
			}
		}
	}
	
//中序遍历	
public static void inOrderUnRecur(Node root) {
		if (root == null) {
			return;
		}
		Stack<Node> stack = new Stack<>();
		while ((root !=null) || (!stack.isEmpty())) {
			while (root != null) {
				stack.push(root);
				root = root.left;
			}
			if (!stack.isEmpty()) {
				root = stack.pop();
				System.out.print(root.value + " ");
				root = root.right;
			}
		}
	}
	
//后序遍历	
public static void posOrderUnRecur(Node root) {
		if (root != null) {
			Stack<Node> s1 = new Stack<Node>();
			Stack<Node> s2 = new Stack<Node>();
			s1.push(root);
			while (!s1.isEmpty()) {
				root = s1.pop();
				s2.push(root);
				if (root.left != null) {
					s1.push(root.left);
				}
				if (root.right != null) {
					s1.push(root.right);
				}
			}
			while (!s2.isEmpty()) {
				System.out.print(s2.pop().value + " ");
			}
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值