二叉查找树之插入算法
package com.pb.datastructure.find; /** * 二叉查找树之插入算法 * @author Administrator */ public class BinarySortTree { private static BinarySortTree tree = new BinarySortTree(); private Node root;//根結點 public void add(int data){ if(null==root){ root=new Node(data,null,null);//如果根结点为空,直接插入根结点 }else{ addTree(root,data); } } /** * @param args */ public static void main(String[] args) { createTree();//创建二叉查找树 System.out.println("插入节点17"); tree.add(17); tree.show(); } /** * 插入节点 * @param root * @param data */ private void addTree(Node root,int data){ if(root.data>data){ if(root.left==null){ root.left=new Node(data,null,null);//如果根节点左子树为空,则直接插入左子树 }else{ addTree(root.left,data); } }else{ if(root.right==null){ root.right=new Node(data,null,null);//如果根节点的右子树为空,则直接插入右子树 }else{ addTree(root.right,data); } } } /** * 控制台显示 */ public void show(){ System.out.println("中序遍历结果为:"); showTree(root); } /** * 显示二叉树 * @author Administrator */ public void showTree(Node node){ if(node.left!=null){ showTree(node.left); } System.out.println(node.data+" "); if(node.right!=null){ showTree(node.right); } } /** * 构建二序查找树 * @author Administrator * */ public static void createTree(){ tree.add(15); tree.add(12); tree.add(9); tree.add(14); tree.add(13); tree.add(19); tree.add(18); tree.add(22); tree.add(23); } class Node { int data;// 当前节点关键字 Node left;// 当前节点左节点 Node right;// 当前节点右节点 public Node(int data, Node left, Node right) { this.data = data; this.left = left; this.right = right; } } }
相关推荐
湾区人工智能 2020-11-20
Pokemogo 2020-11-16
baijingjing 2020-11-16
baijingjing 2020-11-15
Site 2020-11-07
lwnylslwnyls 2020-11-06
justaipanda 2020-11-05
MachineIntellect 2020-11-02
xueyuediana 2020-10-30
GeraldJones 2020-10-30
Tips 2020-10-29
baijingjing 2020-10-28
baijingjing 2020-10-27
硕鼠 2020-10-26
playoffs 2020-10-26
scuyxi 2020-10-25
playoffs 2020-10-25
yise001 2020-10-23