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(); } } }
输入输出样例:
构二叉树图
以样例一为例
这就是样例一构出的树结构