import java.util.Stack;
//分别用递归和非递归方式实现二叉树先序、中序和后序遍历
public class TreeTravel{
//二叉树节点的定义
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data)
{
this.value=data;
}
}
//----------一 递归的二叉树前序、中序、后序遍历
public static void RecurPreOrder(Node head)
{
if(head==null)
{
return ;
}
System.out.print(head.value+" ");
RecurPreOrder(head.left);
RecurPreOrder(head.right);
}
public static void RecurInOrder(Node head)
{
if(head==null)
{
return ;
}
RecurInOrder(head.left);
System.out.print(head.value+" ");
RecurInOrder(head.right);
}
public static void RecurposOrder(Node head)
{
if(head==null)
{
return ;
}
RecurposOrder(head.left);
RecurposOrder(head.right);
System.out.print(head.value+" ");
}
//-----------------------------------------------
//----------二 非递归的二叉树前序、中序、后序遍历(用栈来保存信息)
public static void NoRecurPreOrder(Node head)
{
if(head==null)
{
return ;
}
Stack<Node>stack=new Stack<Node>();
stack.push(head);
while(!stack.isEmpty())
{
head=stack.pop();
System.out.print(head.value+" ");
if(head.right!=null)
{
stack.push(head.right);
}
if(head.left!=null)
{
stack.push(head.left);
用递归和非递归方式实现二叉树先序、中序和后序遍历
最新推荐文章于 2022-10-26 21:35:46 发布
本文详细介绍了如何使用递归和非递归方法来实现二叉树的先序、中序和后序遍历。通过实例解析了每种遍历策略的步骤,帮助读者深入理解二叉树遍历的基本概念和技术。
摘要由CSDN通过智能技术生成