用java構建二叉排序樹,實現先序,中序和後序遍歷
阿新 • • 發佈:2019-01-02
1.基礎知識:
先上圖,舉個例子:
先選遍歷的規則:根節點----左子樹----右子樹 結果為12-9-76-35-22-16-48-46-40-90
中序遍歷的規則:左子樹----根節點----右子樹 結果為9-12-16-22-35-40-46-48-76-90
後序遍歷的規則:左子樹----右子樹----根節點 結果為9-16-22-40-46-48-35-90-76-12
二叉排序樹是遞迴定義的,其結點有左右子樹之分,邏輯上二叉樹有五種基本形態。
2.java程式碼實現
3.程式碼執行結果package cn.edu.ahui; import org.omg.CORBA.PUBLIC_MEMBER; //二叉樹的資料結果 class BinaryTree{ int val;//根節點資料 BinaryTree left;//左子樹 BinaryTree right;//右子樹 public BinaryTree(int val){ this.val = val; this.left = null; this.right = null; } } public class BinaryTreeBuilder { //向二叉樹中插入子樹 public void insert(BinaryTree root, int data){ //二叉排序樹的右節點都比根節點大 if(data > root.val){ if(root.right == null) root.right = new BinaryTree(data); else this.insert(root.right,data);//遞迴插入子節點 } //二叉排序樹的左節點都比根節點小 else{ if(root.left == null) root.left = new BinaryTree(data); else this.insert(root.left, data);//遞迴插入子節點 } } //先序遍歷 public static void preOrder(BinaryTree root){ if(root != null){ System.out.print(root.val+"-"); preOrder(root.left); preOrder(root.right); } } //中序遍歷 public static void inOrder(BinaryTree root){ if(root != null){ inOrder(root.left); System.out.print(root.val+"-"); inOrder(root.right); } } //後序遍歷 public static void postOrder(BinaryTree root){ if(root != null){ postOrder(root.left); postOrder(root.right); System.out.print(root.val+"-"); } } public static void main(String[] args){ int[] a = {12,76,35,22,16,48,90,46,9,40}; BinaryTreeBuilder btb = new BinaryTreeBuilder(); BinaryTree root = new BinaryTree(a[0]); for(int i = 1; i<a.length; i++){ btb.insert(root, a[i]); } System.out.print("先序遍歷:"); preOrder(root); System.out.println(""); System.out.print("中序遍歷:"); inOrder(root); System.out.println(""); System.out.print("後序遍歷:"); postOrder(root); } }
先序遍歷:12-9-76-35-22-16-48-46-40-90-
中序遍歷:9-12-16-22-35-40-46-48-76-90-
後序遍歷:9-16-22-40-46-48-35-90-76-12-