二叉排序树

来源:互联网 发布:南风知我意2书包网 编辑:程序博客网 时间:2024/06/05 06:08

1..什么是二叉查找树

     我们知道链表,由一个结点连着一个结点构成,那么,如果有一种数据结构同样由结点和链接构成,只是不仅仅一个结点连着结点而是两个,是不是可以维护更复杂,更多的关系和信息呢?这就是所谓的二叉树形结构,而二叉查找树是指一个结点的左边所有结点都比它小,而它右边所有的结点都比它的,显然这是一种递归的关系,而且,但它们映射到下面的一条直线上的时候,恰好就是一组中序。如下:

                      6

                   4    8

                 3 5   7 9

        映射345 6 789:

            如上345在6的左子树上,所以都比6小,789在6的右子树上,都比6大。

 

2.二叉排序树的实现理论

     我们要实现二叉排序树,首先定义结点,这一步是类似链表的,由于包含多种信息,所以应该是一个类。核心的操作是查找和插入,我们查找从某一个树(子树)的根节点出发,需要比较大小,判断时候,等价递归的查找左子树或者右子树。而插入节点首先就需要递归的查找和插入。

 

代码实现

 public class BST {private Node root;private class Node{private int key;private String value;private Node left,right;private int n;public Node(int key,String value,int n){this.key = key;this.value = value;this.n = n;}}private int size(Node x){if(x == null)return 0;elsereturn x.n;}public String get(Node x,int key)//从哪一个根节点开始根据键来查找,返回值(键查值){if(x == null)return null;if(key < x.key)return get(x.left, key);else if(key > x.key)return get(x.right, key);elsereturn x.value;}public Node put(Node x, int key, String value)//从哪一个根节点开始查找并插入一个键值对{if(x == null)return new Node(key,value,1);if(key < x.key)x.left =  put(x.left, key ,value);else if(key > x.key)x.right =  put(x.right, key, value);elsex.value = value;x.n = size(x.left) + size(x.right) +1;return x;}public static void main(String[] args){BST bst = new BST();bst.root = bst.put(null, 6, "6");bst.put(bst.root, 4, "4");bst.put(bst.root, 8, "8");bst.put(bst.root, 3, "3");bst.put(bst.root, 5, "5");bst.put(bst.root, 7, "7");bst.put(bst.root, 7, "9");System.out.println(bst.get(bst.root, 8));System.out.println(bst.get(bst.root, 10));}}


0 0
原创粉丝点击