Java实现二叉树建立以及三种遍历

xiaoxiao2021-02-28  89

Java实现二叉树建立以及三种遍历

public class BinTree { static int[] array = {1,2,3,4,5,6,7,8,9}; static List<Node> nodelist = null; /*二叉树节点*/ public static class Node { Node leftChirld; Node rightChirld; int data; public Node(int data) { leftChirld=null; rightChirld=null; this.data=data; } } /*构建二叉树*/ public static void build() { nodelist=new LinkedList<Node>(); for(int node=0;node<array.length;node++) { nodelist.add(new Node(array[node])); } for(int index=0;index<array.length/2-1;index++) { nodelist.get(index).leftChirld = nodelist.get(index*2+1); nodelist.get(index).rightChirld = nodelist.get(index*2+2); } int last = array.length/2-1; nodelist.get(last).leftChirld = nodelist.get(last*2+1); /*判断最后的节点是否有右孩子,有的话就进行添加*/ if (array.length%2==1) { nodelist.get(last).rightChirld = nodelist.get(last*2+2); } } /*先序遍历*/ public static void proOrder(Node node) { if (node==null) { return; } System.out.println(node.data+""); proOrder(node.leftChirld); proOrder(node.rightChirld); } /*中序遍历*/ public static void inOrder(Node node) { if (node==null) { return; } inOrder(node.leftChirld); System.out.println(node.data+""); inOrder(node.rightChirld); } /*后序遍历*/ public static void postOrder(Node node) { if (node==null) { return; } postOrder(node.leftChirld); postOrder(node.rightChirld); System.out.println(node.data+""); } public static void main(String[] args) { BinTree binTree = new BinTree(); binTree.build(); /*获取根节点进行遍历*/ Node root = nodelist.get(0); System.out.println("先序遍历:"); binTree.proOrder(root); System.out.println(""); System.out.println("中序遍历:"); binTree.inOrder(root); System.out.println(""); System.out.println("后序遍历:"); binTree.postOrder(root); } }
转载请注明原文地址: https://www.6miu.com/read-77923.html

最新回复(0)