前序遍历二叉树(非递归)

本文介绍了一种使用栈实现二叉树前序遍历的非递归方法,并提供了完整的Java代码示例。该方法首先将根节点压入栈中,然后循环执行弹出节点并访问的操作,接着将右子节点和左子节点依次压入栈中,直至栈为空。

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

前一篇做了leetcode一道二叉树的hard模式,感觉自己对二叉树的一些数据结构不太敏感,于是打算做个总结,把二叉树的常见遍历方式记录一下,从本篇开始,将按如下顺序实现:

1.前序遍历二叉树(非递归)

2.中序遍历二叉树(非递归)

3.后续遍历二叉树(非递归)

4.前序遍历二叉树(递归)

5.中序遍历二叉树(递归)

6.后续遍历二叉树(递归)


本篇为1.前序遍历二叉树,上代码:

package javatest;

import java.util.Arrays;
import java.util.List;

//Java program to implement iterative preorder traversal
import java.util.Stack;

//A binary tree node
class Node {

	int data;
	Node left, right;

	Node(int item) {
		data = item;
		left = right = null;
	}
}

class BinaryTree {

	Node root;
	
	void iterativePreorder()
	{
		iterativePreorder(root);
	}

	// An iterative process to print preorder traversal of Binary tree
	void iterativePreorder(Node node) {
		
		// Base Case
		if (node == null) {
			return;
		}

		// Create an empty stack and push root to it
		Stack<Node> nodeStack = new Stack<Node>();
		nodeStack.push(root);

		/* Pop all items one by one. Do following for every popped item
		a) print it
		b) push its right child
		c) push its left child
		Note that right child is pushed first so that left is processed first */
		while (nodeStack.empty() == false) {
			
			// Pop the top item from stack and print it
			Node mynode = nodeStack.peek();
			System.out.print(mynode.data + " ");
			nodeStack.pop();

			// Push right and left children of the popped node to stack
			if (mynode.right != null) {
				nodeStack.push(mynode.right);
			}
			if (mynode.left != null) {
				nodeStack.push(mynode.left);
			}
		}
	}

	
}

public class main{
	// driver program to test above functions
		public static void main(String args[]) {
			BinaryTree tree = new BinaryTree();
			tree.root = new Node(10);
			tree.root.left = new Node(8);
			tree.root.right = new Node(2);
			tree.root.left.left = new Node(3);
			tree.root.left.right = new Node(5);
			tree.root.right.left = new Node(2);
			tree.iterativePreorder();

		}
}






这里用了一个栈的数据结构,先把根入栈,然后打印根值,根出栈,押入右子节点,再押入左子节点,循环直到空栈,这个比较好理解,不多解释了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值