本文主要是介绍用递归和非递归方式实现二叉树先序、中序和后序遍历,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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);
这篇关于用递归和非递归方式实现二叉树先序、中序和后序遍历的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!