package tree; public class ArrBinaryTreeDemo { public static void main(String[] args) { int[] arr = {1,2,3,4,5,6,7}; ArrBinaryTree tree = new ArrBinaryTree(arr); System.out.println("前序"); tree.preList(); System.out.println("中序"); tree.infixList(); System.out.println("后序"); tree.postList(); } } class ArrBinaryTree{ int[] arr; public ArrBinaryTree(int[] arr) { this.arr = arr; } public void preList(){ this.preList(0); } public void infixList(){ this.infixList(0); } public void postList(){ this.postList(0); } //前序遍历 public void preList(int index){ System.out.println(arr[index]); if ((index * 2 + 1) < arr.length){ preList(index * 2 + 1); } if ((index * 2 + 2) < arr.length){ preList(index * 2 + 2); } } //中序遍历 public void infixList(int index){ if ((index * 2 + 1) < arr.length){ infixList(index * 2 + 1); } System.out.println(arr[index]); if ((index * 2 + 2) < arr.length){ infixList(index * 2 + 2); } } //后序遍历 public void postList(int index){ if ((index * 2 + 1) < arr.length){ postList(index * 2 + 1); } if ((index * 2 + 2) < arr.length){ postList(index * 2 + 2); } System.out.println(arr[index]); } }
Java数据结构《顺序存储二叉树》的前序中序后序遍历
最新推荐文章于 2022-07-02 14:51:28 发布