Java構建二叉樹搜索並輸出
二叉樹搜索(查找)樹 特性:
二叉排序樹(Binary Sort Tree)又稱二叉查找樹。 它或者是一棵空樹;或者是具有下列性質的二叉樹:
(1)若左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;
(2)若右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;
(3)左、右子樹也分別為二叉排序樹;
package com.algorithm; import java.util.Scanner; //搜索二叉樹構建測試數據 //9 //5 7 6 9 2 1 3 8 4 //20 //50 31 45 65 78 98 12 3 45 14 78 23 56 20 21 4 34 94 46 84 //節點類 class Node{ public Node left = null; public Node right = null; public int data = 0; } public class BST { //構建搜索二叉樹 public static void buildingBST(Node node, int m){ if(node.data <= 0){ //無創建 node.data = m; }else if(node.data > m){ if(node.left == null){ node.left = new Node(); node.left.data = m; }else{ buildingBST(node.left, m); } }else{ if(node.right == null){ node.right = new Node(); node.right.data = m; }else{ buildingBST(node.right, m); } } } //輸出搜索二叉樹 public static void printBST(Node node){ if(node == null){ return; } printBST(node.left); //左節點 System.out.print(node.data+" "); printBST(node.right); //右節點 } public static void main(String[] args) { Scanner cin = new Scanner(System.in); while(cin.hasNext()){ int n = cin.nextInt(); Node node = new Node(); while(n-- > 0){ int m = cin.nextInt(); buildingBST(node, m); //構建搜索二叉樹 } //輸出搜索二叉樹 printBST(node); System.out.println(); } } }
輸入輸出樣例:
構二叉樹圖
以樣例一為例
這就是樣例一構出的樹結構