使用栈遍历二叉树(非递归)

本文详细介绍了二叉树的三种遍历算法:先序遍历、中序遍历和后序遍历。先序遍历遵循根左右的顺序,中序遍历为左根右,后序遍历则为左右根。通过具体实现代码,读者可以深入理解每种遍历方式的工作原理。

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

先序遍历

	/**
	 * 先序遍历
	 * 根 左 右
	 */
	@Override
	public List preOrderTraverse() {
		List list = new ArrayList();
		Deque<Node> stack = new LinkedList();
		Node cursor = root; // 根节点
		
		while (!stack.isEmpty() || cursor != null) {
			
			// 遍历左子树
			while (cursor != null) {
				stack.push(cursor);
				list.add(cursor.data);
				cursor = cursor.leftChild;
			}
			
			// 左子树遍历完成后,出栈,在遍历右子树
			if (!stack.isEmpty()) {
				cursor = stack.pop();
				cursor = cursor.rightChild;
			}
		}
		
		return list;
	}

中序遍历

	/**
	 * 中序遍历
	 * 左 根 右
	 */
	@Override
	public List inOrderTraverse() {
		List list = new ArrayList();
		Deque<Node> stack = new LinkedList();
		Node cursor = root; // 根节点
		
		while (!stack.isEmpty() || cursor != null) {
			
			// 遍历左子树
			while (cursor != null) {
				stack.push(cursor);
				cursor = cursor.leftChild;
			}
			
			// 左子树遍历完成后,出栈,在遍历右子树
			if (!stack.isEmpty()) {
				cursor = stack.pop();
				list.add(cursor.data);
				cursor = cursor.rightChild;
			}
		} 
		
		return list;
	}

后序遍历

	/**
	 * 后序遍历
	 * 左 右 根
	 * 遍历方式和先序遍历相同,只不过先序遍历是从左子树开始遍历的,
	 * 而后序遍历是从右子树开始遍历的,最后把所得到的结果翻转一下就可以了
	 */
	@Override
	public List postOrderTraverse() {
		List list = new ArrayList();

		Deque<Node> stack = new LinkedList();
		Node cursor = root; // 根节点
		
		while (cursor != null || !stack.isEmpty()) {
			while (cursor != null) {
				stack.push(cursor);
				list.add(cursor.data);
				cursor = cursor.rightChild;
			}
			
			if (!stack.isEmpty()) {
				cursor = stack.pop();
				cursor = cursor.leftChild;
			}
		}
		Collections.reverse(list); // 反转list
		return list;
	}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值