Java建立二叉排序樹和平衡樹
阿新 • • 發佈:2018-12-13
建立二叉排序樹,是從前往後掃描陣列,可以不保證高度最小,從頭節點依次向下尋找要插入的適當位置。 建立平衡樹,可以先將陣列進行排序,然後選取中間元素作為根節點,陣列中間元素左邊的元素為根節點的左子樹,陣列中間右邊的元素為根節點的右子樹。 再對右子樹和右子樹選取中間節點,進行建樹操作。 程式碼:
package easy; import easy.JavaTree; import easy.TreeNode; public class BinarySortTree { public static void main(String[] args) { // TODO Auto-generated method stub // int shuzu []= {3,1,2,5,0,7,9,8}; // TreeNode root = new TreeNode(shuzu[0]); //以3這個數為根節點 // for( int i = 1 ; i < shuzu.length ; i ++){ // // SortBinaryTree(root, shuzu[i]); // } int shuzu []= {0,1,2,3,5,7,8,9}; preorder(createminheighttree(shuzu, 0, shuzu.length -1)); } //遞迴陣列從頭到尾建立二叉樹,可能不平衡 public static TreeNode SortBinaryTree(TreeNode node,int i){ if(node == null){ node = new TreeNode(i); return node; } else{ if(i <= node.val){ node.left = SortBinaryTree(node.left, i); } else{ node.right = SortBinaryTree(node.right,i); } return node; } } //建立平衡二叉排序樹 public static TreeNode createminheighttree(int a [] , int start , int end ){ if(end < start){ return null; } int min = (start + end) / 2; TreeNode root = new TreeNode(a[min]); root.left = createminheighttree(a, start, min -1); root.right = createminheighttree(a, min+ 1, end); return root; } public static void preorder(TreeNode root){ if(root!=null){ System.out.println(root.val); preorder(root.left); preorder(root.right); } } }