浅析数据结构

 

二叉树

  二叉树应用广泛,多种数据结构基于二叉树,如AVL平衡二叉树,红黑树。

  这次就复盘一下这个简单,同时又非常重要的数据结构。

 定义

  二叉树是一棵树

  二叉树的每个结点都最多有两个子结点:左子树,右子树

二叉排序树

  二叉排序树是一颗二叉树

  二叉排序树的左孩子比父节点大,右孩子比父节点小

二叉排序树的实现(Java)

1.树的定义:

  我们定义一个二叉树类,继承Comparable以实现泛型对比

  在类中定义一个结点内部类Node<T>

  详细如下:

//因为使用了泛型,需要继承Comparable类
class BinaryTree<T extends Comparable<T>> {
    private Node<T> rootNode = null;
  // 节点
    class Node<T extends Comparable<T>> {
        // 左孩子
        Node<T> leftSon;
        // 右孩子
        Node<T> rightSon;
        // 父亲
        Node<T> parent;
        T key;
Node() {}
Node(T t) {
this.key = t; } } }

 2.添加元素

    // 添加节点
    public void add(T t) {
        int result;
        Node<T> newNode = new Node<>(t);
        Node<T> target = null;
        Node<T> temp = this.rootNode;
        // 寻找对应父节点
        while (temp != null) {
            target = temp;
            result = temp.key.compareTo(t);
            if (result > 0) {
                temp = temp.leftSon;
            }else{
                temp = temp.rightSon;
            }
        }
        newNode.parent = target;
        // 判断当前树是否为空
        if(target!=null){
            result = target.key.compareTo(t);
            if(result > 0){
                target.leftSon = newNode;
            }else{
                target.rightSon = newNode;
            }
        }else{
            this.rootNode = newNode;
        }
    }

3.遍历元素

    // 使用中序遍历
    public void doLDR(){
        inOrderTraverse1(rootNode);
    }
    // 中序遍历算法
    public void inOrderTraverse1(Node<T> root) { 
        if (root != null) {  
            inOrderTraverse1(root.leftSon);  
            System.out.print(root.key+"  ");  
            inOrderTraverse1(root.rightSon);  
        } 
    }
原文地址:https://www.cnblogs.com/joe2047/p/10407752.html