【数据结构基础】树 - 二叉搜索树(BST)

【数据结构】二叉搜索树 思路:首先检查树是否为空,如果树为空就创建一个新的节点让_root指向这个节点,因为我们构建的树要符合二叉搜索树的特点所以如果要继续插入新的元素就和根节点进行比较,比根节点的值大就往根节点的右边走,如果比根节点的值小就往根节点的左边走。从根节点开始查找, 如果val大于根节点的键值, 去根的右边找;第二种情况:首先判断要删除的节点是父节点的左孩子还是右孩子,然后让对应的父节点的位置连接上自己的左孩子。第三种情况:首先判断要删除的节点是父节点的左孩子还是右孩子,然后让对应的父节点的位置连接上自己的右孩子。 阅读详情
本文主要介绍 二叉树中最基本的二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。

BST的定义

在二叉查找树中:

  • 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;

  • 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;

  • 任意节点的左、右子树也分别为二叉查找树。

  • 没有键值相等的节点。

动画效果请参考 BST

BST的实现

节点

BSTree是二叉树,它保存了二叉树的根节点mRoot;mRoot是BSTNode类型,而BSTNode是二叉查找树的节点,它是BSTree的内部类。BSTNode包含二叉查找树的几个基本信息:

  • key -- 它是关键字,是用来对二叉查找树的节点进行排序的。

  • left -- 它指向当前节点的左孩子。

  • right -- 它指向当前节点的右孩子。

  • parent -- 它指向当前节点的父结点。

public class BSTree<T extends Comparable<T>> {

    private BSTNode<T> mRoot;    // 根结点

    public class BSTNode<T extends Comparable<T>> {
        T key;                // 关键字(键值)
        BSTNode<T> left;      // 左孩子
        BSTNode<T> right;     // 右孩子
        BSTNode<T> parent;    // 父结点

        public BSTNode(T key, BSTNode<T> parent, BSTNode<T> left, BSTNode<T> right) {
            this.key = key;
            this.parent = parent;
            this.left = left;
            this.right = right;
        }
    }

        ......
}

遍历

这里讲解前序遍历、中序遍历、后序遍历3种方式。

前序遍历

若二叉树非空,则执行以下操作:

  • 访问根结点;

  • 先序遍历左子树;

  • 先序遍历右子树。

private void preOrder(BSTNode<T> tree) {
    if(tree != null) {
        System.out.print(tree.key+" ");
        preOrder(tree.left);
        preOrder(tree.right);
    }
}

public void preOrder() {
    preOrder(mRoot);
}
中序遍历

若二叉树非空,则执行以下操作:

  • 中序遍历左子树;

  • 访问根结点;

  • 中序遍历右子树。

private void inOrder(BSTNode<T> tree) {
    if(tree != null) {
        inOrder(tree.left);
        System.out.print(tree.key+" ");
        inOrder(tree.right);
    }
}

public void inOrder() {
    inOrder(mRoot);
}
后序遍历

若二叉树非空,则执行以下操作:

  • 后序遍历左子树;

  • 后序遍历右子树;

  • 访问根结点。

private void postOrder(BSTNode<T> tree) {
    if(tree != null)
    {
        postOrder(tree.left);
        postOrder(tree.right);
        System.out.print(tree.key+" ");
    }
}

public void postOrder() {
    postOrder(mRoot);
}

看看下面这颗树的各种遍历方式:

对于上面的二叉树而言,

  • 前序遍历结果: 8 3 1 6 4 7 10 14 13

  • 中序遍历结果: 1 3 4 6 7 8 10 13 14

  • 后序遍历结果: 1 4 7 6 3 13 14 10 8

查找

  • 递归版本的代码

/*
 * (递归实现)查找"二叉树x"中键值为key的节点
 */
private BSTNode<T> search(BSTNode<T> x, T key) {
    if (x==null)
        return x;

    int cmp = key.compareTo(x.key);
    if (cmp < 0)
        return search(x.left, key);
    else if (cmp > 0)
        return search(x.right, key);
    else
        return x;
}

public BSTNode<T> search(T key) {
    return search(mRoot, key);
}
  • 非递归版本的代码

/*
 * (非递归实现)查找"二叉树x"中键值为key的节点
 */
private BSTNode<T> iterativeSearch(BSTNode<T> x, T key) {
    while (x!=null) {
        int cmp = key.compareTo(x.key);

        if (cmp < 0) 
            x = x.left;
        else if (cmp > 0) 
            x = x.right;
        else
            return x;
    }

    return x;
}

public BSTNode<T> iterativeSearch(T key) {
    return iterativeSearch(mRoot, key);
}

最大值和最小值

  • 查找最大结点

/* 
 * 查找最大结点: 返回tree为根结点的二叉树的最大结点。
 */
private BSTNode<T> maximum(BSTNode<T> tree) {
    if (tree == null)
        return null;

    while(tree.right != null)
        tree = tree.right;
    return tree;
}

public T maximum() {
    BSTNode<T> p = maximum(mRoot);
    if (p != null)
        return p.key;

    return null;
}
  • 查找最小结点

/* 
 * 查找最小结点: 返回tree为根结点的二叉树的最小结点。
 */
private BSTNode<T> minimum(BSTNode<T> tree) {
    if (tree == null)
        return null;

    while(tree.left != null)
        tree = tree.left;
    return tree;
}

public T minimum() {
    BSTNode<T> p = minimum(mRoot);
    if (p != null)
        return p.key;

    return null;
}

前驱和后继

节点的前驱: 是该节点的左子树中的最大节点。 节点的后继: 是该节点的右子树中的最小节点。

  • 查找前驱节点

/* 
 * 找结点(x)的前驱结点。即,查找"二叉树中数据值小于该结点"的"最大结点"。
 */
public BSTNode<T> predecessor(BSTNode<T> x) {
    // 如果x存在左孩子,则"x的前驱结点"为 "以其左孩子为根的子树的最大结点"。
    if (x.left != null)
        return maximum(x.left);

    // 如果x没有左孩子。则x有以下两种可能: 
    // (01) x是"一个右孩子",则"x的前驱结点"为 "它的父结点"。
    // (01) x是"一个左孩子",则查找"x的最低的父结点,并且该父结点要具有右孩子",找到的这个"最低的父结点"就是"x的前驱结点"。
    BSTNode<T> y = x.parent;
    while ((y!=null) && (x==y.left)) {
        x = y;
        y = y.parent;
    }

    return y;
}
  • 查找后继节点

/* 
 * 找结点(x)的后继结点。即,查找"二叉树中数据值大于该结点"的"最小结点"。
 */
public BSTNode<T> successor(BSTNode<T> x) {
    // 如果x存在右孩子,则"x的后继结点"为 "以其右孩子为根的子树的最小结点"。
    if (x.right != null)
        return minimum(x.right);

    // 如果x没有右孩子。则x有以下两种可能: 
    // (01) x是"一个左孩子",则"x的后继结点"为 "它的父结点"。
    // (02) x是"一个右孩子",则查找"x的最低的父结点,并且该父结点要具有左孩子",找到的这个"最低的父结点"就是"x的后继结点"。
    BSTNode<T> y = x.parent;
    while ((y!=null) && (x==y.right)) {
        x = y;
        y = y.parent;
    }

    return y;
}

插入

/* 
 * 将结点插入到二叉树中
 *
 * 参数说明: 
 *     tree 二叉树的
 *     z 插入的结点
 */
private void insert(BSTree<T> bst, BSTNode<T> z) {
    int cmp;
    BSTNode<T> y = null;
    BSTNode<T> x = bst.mRoot;

    // 查找z的插入位置
    while (x != null) {
        y = x;
        cmp = z.key.compareTo(x.key);
        if (cmp < 0)
            x = x.left;
        else
            x = x.right;
    }

    z.parent = y;
    if (y==null)
        bst.mRoot = z;
    else {
        cmp = z.key.compareTo(y.key);
        if (cmp < 0)
            y.left = z;
        else
            y.right = z;
    }
}

/* 
 * 新建结点(key),并将其插入到二叉树中
 *
 * 参数说明: 
 *     tree 二叉树的根结点
 *     key 插入结点的键值
 */
public void insert(T key) {
    BSTNode<T> z=new BSTNode<T>(key,null,null,null);

    // 如果新建结点失败,则返回。
    if (z != null)
        insert(this, z);
}

删除

/* 
 * 删除结点(z),并返回被删除的结点
 *
 * 参数说明: 
 *     bst 二叉树
 *     z 删除的结点
 */
private BSTNode<T> remove(BSTree<T> bst, BSTNode<T> z) {
    BSTNode<T> x=null;
    BSTNode<T> y=null;

    if ((z.left == null) || (z.right == null) )
        y = z;
    else
        y = successor(z);

    if (y.left != null)
        x = y.left;
    else
        x = y.right;

    if (x != null)
        x.parent = y.parent;

    if (y.parent == null)
        bst.mRoot = x;
    else if (y == y.parent.left)
        y.parent.left = x;
    else
        y.parent.right = x;

    if (y != z) 
        z.key = y.key;

    return y;
}

/* 
 * 删除结点(z),并返回被删除的结点
 *
 * 参数说明: 
 *     tree 二叉树的根结点
 *     z 删除的结点
 */
public void remove(T key) {
    BSTNode<T> z, node; 

    if ((z = search(mRoot, key)) != null)
        if ( (node = remove(this, z)) != null)
            node = null;
}

打印

/*
 * 打印"二叉查找树"
 *
 * key        -- 节点的键值 
 * direction  --  0,表示该节点是根节点;
 *               -1,表示该节点是它的父结点的左孩子;
 *                1,表示该节点是它的父结点的右孩子。
 */
private void print(BSTNode<T> tree, T key, int direction) {

    if(tree != null) {

        if(direction==0)    // tree是根节点
            System.out.printf("%2d is root\n", tree.key);
        else                // tree是分支节点
            System.out.printf("%2d is %2d's %6s child\n", tree.key, key, direction==1?"right" : "left");

        print(tree.left, tree.key, -1);
        print(tree.right,tree.key,  1);
    }
}

public void print() {
    if (mRoot != null)
        print(mRoot, mRoot.key, 0);
}

销毁

/*
 * 销毁二叉树
 */
private void destroy(BSTNode<T> tree) {
    if (tree==null)
        return ;

    if (tree.left != null)
        destroy(tree.left);
    if (tree.right != null)
        destroy(tree.right);

    tree=null;
}

public void clear() {
    destroy(mRoot);
    mRoot = null;
}

测试程序

下面对测试程序的流程进行分析!

  • 新建"二叉查找树"root。

  • 向二叉查找树中依次插入1,5,4,3,2,6 。如下图所示:

  • 遍历和查找

插入1,5,4,3,2,6之后,得到的二叉查找树如下:

前序遍历结果: 154326 
中序遍历结果: 123456 
后序遍历结果: 234651 
最小值是1,而最大值是6。
  • 删除节点4。如下图所示:

  • 重新遍历该二叉查找树。

中序遍历结果: 1 2 4 5 6

代码和测试代码

代码实现

/**
 * Java 语言: 二叉查找树
 *
 * @author skywang
 * @date 2013/11/07
 */

public class BSTree<T extends Comparable<T>> {

    private BSTNode<T> mRoot;    // 根结点

    public class BSTNode<T extends Comparable<T>> {
        T key;                // 关键字(键值)
        BSTNode<T> left;    // 左孩子
        BSTNode<T> right;    // 右孩子
        BSTNode<T> parent;    // 父结点

        public BSTNode(T key, BSTNode<T> parent, BSTNode<T> left, BSTNode<T> right) {
            this.key = key;
            this.parent = parent;
            this.left = left;
            this.right = right;
        }

        public T getKey() {
            return key;
        }

        public String toString() {
            return "key:"+key;
        }
    }

    public BSTree() {
        mRoot=null;
    }

    /*
     * 前序遍历"二叉树"
     */
    private void preOrder(BSTNode<T> tree) {
        if(tree != null) {
            System.out.print(tree.key+" ");
            preOrder(tree.left);
            preOrder(tree.right);
        }
    }

    public void preOrder() {
        preOrder(mRoot);
    }

    /*
     * 中序遍历"二叉树"
     */
    private void inOrder(BSTNode<T> tree) {
        if(tree != null) {
            inOrder(tree.left);
            System.out.print(tree.key+" ");
            inOrder(tree.right);
        }
    }

    public void inOrder() {
        inOrder(mRoot);
    }


    /*
     * 后序遍历"二叉树"
     */
    private void postOrder(BSTNode<T> tree) {
        if(tree != null)
        {
            postOrder(tree.left);
            postOrder(tree.right);
            System.out.print(tree.key+" ");
        }
    }

    public void postOrder() {
        postOrder(mRoot);
    }


    /*
     * (递归实现)查找"二叉树x"中键值为key的节点
     */
    private BSTNode<T> search(BSTNode<T> x, T key) {
        if (x==null)
            return x;

        int cmp = key.compareTo(x.key);
        if (cmp < 0)
            return search(x.left, key);
        else if (cmp > 0)
            return search(x.right, key);
        else
            return x;
    }

    public BSTNode<T> search(T key) {
        return search(mRoot, key);
    }

    /*
     * (非递归实现)查找"二叉树x"中键值为key的节点
     */
    private BSTNode<T> iterativeSearch(BSTNode<T> x, T key) {
        while (x!=null) {
            int cmp = key.compareTo(x.key);

            if (cmp < 0) 
                x = x.left;
            else if (cmp > 0) 
                x = x.right;
            else
                return x;
        }

        return x;
    }

    public BSTNode<T> iterativeSearch(T key) {
        return iterativeSearch(mRoot, key);
    }

    /* 
     * 查找最小结点: 返回tree为根结点的二叉树的最小结点。
     */
    private BSTNode<T> minimum(BSTNode<T> tree) {
        if (tree == null)
            return null;

        while(tree.left != null)
            tree = tree.left;
        return tree;
    }

    public T minimum() {
        BSTNode<T> p = minimum(mRoot);
        if (p != null)
            return p.key;

        return null;
    }
     
    /* 
     * 查找最大结点: 返回tree为根结点的二叉树的最大结点。
     */
    private BSTNode<T> maximum(BSTNode<T> tree) {
        if (tree == null)
            return null;

        while(tree.right != null)
            tree = tree.right;
        return tree;
    }

    public T maximum() {
        BSTNode<T> p = maximum(mRoot);
        if (p != null)
            return p.key;

        return null;
    }

    /* 
     * 找结点(x)的后继结点。即,查找"二叉树中数据值大于该结点"的"最小结点"。
     */
    public BSTNode<T> successor(BSTNode<T> x) {
        // 如果x存在右孩子,则"x的后继结点"为 "以其右孩子为根的子树的最小结点"。
        if (x.right != null)
            return minimum(x.right);

        // 如果x没有右孩子。则x有以下两种可能: 
        // (01) x是"一个左孩子",则"x的后继结点"为 "它的父结点"。
        // (02) x是"一个右孩子",则查找"x的最低的父结点,并且该父结点要具有左孩子",找到的这个"最低的父结点"就是"x的后继结点"。
        BSTNode<T> y = x.parent;
        while ((y!=null) && (x==y.right)) {
            x = y;
            y = y.parent;
        }

        return y;
    }
     
    /* 
     * 找结点(x)的前驱结点。即,查找"二叉树中数据值小于该结点"的"最大结点"。
     */
    public BSTNode<T> predecessor(BSTNode<T> x) {
        // 如果x存在左孩子,则"x的前驱结点"为 "以其左孩子为根的子树的最大结点"。
        if (x.left != null)
            return maximum(x.left);

        // 如果x没有左孩子。则x有以下两种可能: 
        // (01) x是"一个右孩子",则"x的前驱结点"为 "它的父结点"。
        // (01) x是"一个左孩子",则查找"x的最低的父结点,并且该父结点要具有右孩子",找到的这个"最低的父结点"就是"x的前驱结点"。
        BSTNode<T> y = x.parent;
        while ((y!=null) && (x==y.left)) {
            x = y;
            y = y.parent;
        }

        return y;
    }

    /* 
     * 将结点插入到二叉树中
     *
     * 参数说明: 
     *     tree 二叉树的
     *     z 插入的结点
     */
    private void insert(BSTree<T> bst, BSTNode<T> z) {
        int cmp;
        BSTNode<T> y = null;
        BSTNode<T> x = bst.mRoot;

        // 查找z的插入位置
        while (x != null) {
            y = x;
            cmp = z.key.compareTo(x.key);
            if (cmp < 0)
                x = x.left;
            else
                x = x.right;
        }

        z.parent = y;
        if (y==null)
            bst.mRoot = z;
        else {
            cmp = z.key.compareTo(y.key);
            if (cmp < 0)
                y.left = z;
            else
                y.right = z;
        }
    }

    /* 
     * 新建结点(key),并将其插入到二叉树中
     *
     * 参数说明: 
     *     tree 二叉树的根结点
     *     key 插入结点的键值
     */
    public void insert(T key) {
        BSTNode<T> z=new BSTNode<T>(key,null,null,null);

        // 如果新建结点失败,则返回。
        if (z != null)
            insert(this, z);
    }

    /* 
     * 删除结点(z),并返回被删除的结点
     *
     * 参数说明: 
     *     bst 二叉树
     *     z 删除的结点
     */
    private BSTNode<T> remove(BSTree<T> bst, BSTNode<T> z) {
        BSTNode<T> x=null;
        BSTNode<T> y=null;

        if ((z.left == null) || (z.right == null) )
            y = z;
        else
            y = successor(z);

        if (y.left != null)
            x = y.left;
        else
            x = y.right;

        if (x != null)
            x.parent = y.parent;

        if (y.parent == null)
            bst.mRoot = x;
        else if (y == y.parent.left)
            y.parent.left = x;
        else
            y.parent.right = x;

        if (y != z) 
            z.key = y.key;

        return y;
    }

    /* 
     * 删除结点(z),并返回被删除的结点
     *
     * 参数说明: 
     *     tree 二叉树的根结点
     *     z 删除的结点
     */
    public void remove(T key) {
        BSTNode<T> z, node; 

        if ((z = search(mRoot, key)) != null)
            if ( (node = remove(this, z)) != null)
                node = null;
    }

    /*
     * 销毁二叉树
     */
    private void destroy(BSTNode<T> tree) {
        if (tree==null)
            return ;

        if (tree.left != null)
            destroy(tree.left);
        if (tree.right != null)
            destroy(tree.right);

        tree=null;
    }

    public void clear() {
        destroy(mRoot);
        mRoot = null;
    }

    /*
     * 打印"二叉查找树"
     *
     * key        -- 节点的键值 
     * direction  --  0,表示该节点是根节点;
     *               -1,表示该节点是它的父结点的左孩子;
     *                1,表示该节点是它的父结点的右孩子。
     */
    private void print(BSTNode<T> tree, T key, int direction) {

        if(tree != null) {

            if(direction==0)    // tree是根节点
                System.out.printf("%2d is root\n", tree.key);
            else                // tree是分支节点
                System.out.printf("%2d is %2d's %6s child\n", tree.key, key, direction==1?"right" : "left");

            print(tree.left, tree.key, -1);
            print(tree.right,tree.key,  1);
        }
    }

    public void print() {
        if (mRoot != null)
            print(mRoot, mRoot.key, 0);
    }
}

测试代码

/**
 * Java 语言: 二叉查找树
 *
 * @author skywang
 * @date 2013/11/07
 */
public class BSTreeTest {

    private static final int arr[] = {1,5,4,3,2,6};

    public static void main(String[] args) {
        int i, ilen;
        BSTree<Integer> tree=new BSTree<Integer>();

        System.out.print("== 依次添加: ");
        ilen = arr.length;
        for(i=0; i<ilen; i++) {
            System.out.print(arr[i]+" ");
            tree.insert(arr[i]);
        }

        System.out.print("\n== 前序遍历: ");
        tree.preOrder();

        System.out.print("\n== 中序遍历: ");
        tree.inOrder();

        System.out.print("\n== 后序遍历: ");
        tree.postOrder();
        System.out.println();

        System.out.println("== 最小值: "+ tree.minimum());
        System.out.println("== 最大值: "+ tree.maximum());
        System.out.println("== 树的详细信息: ");
        tree.print();

        System.out.print("\n== 删除根节点: "+ arr[3]);
        tree.remove(arr[3]);

        System.out.print("\n== 中序遍历: ");
        tree.inOrder();
        System.out.println();

        // 销毁二叉树
        tree.clear();
    }
}

测试结果

== 依次添加: 1 5 4 3 2 6 
== 前序遍历: 1 5 4 3 2 6 
== 中序遍历: 1 2 3 4 5 6 
== 后序遍历: 2 3 4 6 5 1 
== 最小值: 1
== 最大值: 6
== 树的详细信息: 
is root
is  1's  right child
is  5's   left child
is  4's   left child
is  3's   left child
is  5's  right child

== 删除根节点: 3
== 中序遍历: 1 2 4 5 6

BST相关题目

二叉查找树(BST): 根节点大于等于左子树所有节点,小于等于右子树所有节点。

二叉查找树中序遍历有序。

修剪二叉查找树

669. Trim a Binary Search Tree (Easy)

Input:

    3
   / \
  0   4
   \
    2
   /
  1

  L = 1
  R = 3

Output:

      3
     /
   2
  /
 1

题目描述: 只保留值在 L ~ R 之间的节点

public TreeNode trimBST(TreeNode root, int L, int R) {
    if (root == null) return null;
    if (root.val > R) return trimBST(root.left, L, R);
    if (root.val < L) return trimBST(root.right, L, R);
    root.left = trimBST(root.left, L, R);
    root.right = trimBST(root.right, L, R);
    return root;
}

寻找二叉查找树的第 k 个元素

230. Kth Smallest Element in a BST (Medium)

中序遍历解法:

private int cnt = 0;
private int val;

public int kthSmallest(TreeNode root, int k) {
    inOrder(root, k);
    return val;
}

private void inOrder(TreeNode node, int k) {
    if (node == null) return;
    inOrder(node.left, k);
    cnt++;
    if (cnt == k) {
        val = node.val;
        return;
    }
    inOrder(node.right, k);
}

递归解法:

public int kthSmallest(TreeNode root, int k) {
    int leftCnt = count(root.left);
    if (leftCnt == k - 1) return root.val;
    if (leftCnt > k - 1) return kthSmallest(root.left, k);
    return kthSmallest(root.right, k - leftCnt - 1);
}

private int count(TreeNode node) {
    if (node == null) return 0;
    return 1 + count(node.left) + count(node.right);
}

把二叉查找树每个节点的值都加上比它大的节点的值

Convert BST to Greater Tree (Easy)

Input: The root of a Binary Search Tree like this:

              5
            /   \
           2     13

Output: The root of a Greater Tree like this:

             18
            /   \
          20     13

先遍历右子树。

private int sum = 0;

public TreeNode convertBST(TreeNode root) {
    traver(root);
    return root;
}

private void traver(TreeNode node) {
    if (node == null) return;
    traver(node.right);
    sum += node.val;
    node.val = sum;
    traver(node.left);
}

二叉查找树的最近公共祖先

235. Lowest Common Ancestor of a Binary Search Tree (Easy)

        _______6______
      /                \
  ___2__             ___8__
 /      \           /      \
0        4         7        9
        /  \
       3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
    if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
    return root;
}

二叉树的最近公共祖先

236. Lowest Common Ancestor of a Binary Tree (Medium)

       _______3______
      /              \
  ___5__           ___1__
 /      \         /      \
6        2       0        8
        /  \
       7    4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q) return root;
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    return left == null ? right : right == null ? left : root;
}

从有序数组中构造二叉查找树

108. Convert Sorted Array to Binary Search Tree (Easy)

public TreeNode sortedArrayToBST(int[] nums) {
    return toBST(nums, 0, nums.length - 1);
}

private TreeNode toBST(int[] nums, int sIdx, int eIdx){
    if (sIdx > eIdx) return null;
    int mIdx = (sIdx + eIdx) / 2;
    TreeNode root = new TreeNode(nums[mIdx]);
    root.left =  toBST(nums, sIdx, mIdx - 1);
    root.right = toBST(nums, mIdx + 1, eIdx);
    return root;
}

根据有序链表构造平衡的二叉查找树

109. Convert Sorted List to Binary Search Tree (Medium)

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5
public TreeNode sortedListToBST(ListNode head) {
    if (head == null) return null;
    if (head.next == null) return new TreeNode(head.val);
    ListNode preMid = preMid(head);
    ListNode mid = preMid.next;
    preMid.next = null;  // 断开链表
    TreeNode t = new TreeNode(mid.val);
    t.left = sortedListToBST(head);
    t.right = sortedListToBST(mid.next);
    return t;
}

private ListNode preMid(ListNode head) {
    ListNode slow = head, fast = head.next;
    ListNode pre = head;
    while (fast != null && fast.next != null) {
        pre = slow;
        slow = slow.next;
        fast = fast.next.next;
    }
    return pre;
}

在二叉查找树中寻找两个节点,使它们的和为一个给定值

653. Two Sum IV - Input is a BST (Easy)

Input:

    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True

使用中序遍历得到有序数组之后,再利用双指针对数组进行查找。

应该注意到,这一题不能用分别在左右子树两部分来处理这种思想,因为两个待求的节点可能分别在左右子树中。

public boolean findTarget(TreeNode root, int k) {
    List<Integer> nums = new ArrayList<>();
    inOrder(root, nums);
    int i = 0, j = nums.size() - 1;
    while (i < j) {
        int sum = nums.get(i) + nums.get(j);
        if (sum == k) return true;
        if (sum < k) i++;
        else j--;
    }
    return false;
}

private void inOrder(TreeNode root, List<Integer> nums) {
    if (root == null) return;
    inOrder(root.left, nums);
    nums.add(root.val);
    inOrder(root.right, nums);
}

在二叉查找树中查找两个节点之差的最小绝对值

530. Minimum Absolute Difference in BST (Easy)

Input:

   1
    \
     3
    /
   2

Output:

1

利用二叉查找树的中序遍历为有序的性质,计算中序遍历中临近的两个节点之差的绝对值,取最小值。

private int minDiff = Integer.MAX_VALUE;
private TreeNode preNode = null;

public int getMinimumDifference(TreeNode root) {
    inOrder(root);
    return minDiff;
}

private void inOrder(TreeNode node) {
    if (node == null) return;
    inOrder(node.left);
    if (preNode != null) minDiff = Math.min(minDiff, node.val - preNode.val);
    preNode = node;
    inOrder(node.right);
}

寻找二叉查找树中出现次数最多的值

501. Find Mode in Binary Search Tree (Easy)

   1
    \
     2
    /
   2

return [2].

答案可能不止一个,也就是有多个值出现的次数一样多。

private int curCnt = 1;
private int maxCnt = 1;
private TreeNode preNode = null;

public int[] findMode(TreeNode root) {
    List<Integer> maxCntNums = new ArrayList<>();
    inOrder(root, maxCntNums);
    int[] ret = new int[maxCntNums.size()];
    int idx = 0;
    for (int num : maxCntNums) {
        ret[idx++] = num;
    }
    return ret;
}

private void inOrder(TreeNode node, List<Integer> nums) {
    if (node == null) return;
    inOrder(node.left, nums);
    if (preNode != null) {
        if (preNode.val == node.val) curCnt++;
        else curCnt = 1;
    }
    if (curCnt > maxCnt) {
        maxCnt = curCnt;
        nums.clear();
        nums.add(node.val);
    } else if (curCnt == maxCnt) {
        nums.add(node.val);
    }
    preNode = node;
    inOrder(node.right, nums);
}
数据结构 : 二叉搜索树(BST) ????‍???? ????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍????????‍?????? 阅读详情

相关推荐

二叉查找树(BST)(算法笔记)

数据结构的目的是用来优化数据的使用效率,这是数据结构的本质。二叉查找树是一种特殊形态的二叉树,又称为排序二叉树、二叉搜索树、二叉排序树。对树上的每个节点,都满足其左子树上所有结点的数据域均小于或等于根节点的数据域,右子树上所有结点的数据域均大于根结点的数据域。单独使用一颗普通的二叉树对提高数据使用效率没有太大帮助,因为普通二叉树数据之间不存在明显的逻辑联系,在进行插入时,无法提供性质满足插入位置的确定,即插入位置的选择完全是随机的,所以并不会直接考察普通二叉树的插入和删除操作。

Arabot_的博客 1875

【数据结构】二叉查找树(BST)

二叉查找树(Binary Search Tree,BST),又叫做二叉排序树、二叉搜索树,是一种对查找和排序都有用的特殊二叉树。二叉查找树的特性:左子树

m0_46628950的博客 8174

【数据结构】判断给定的二叉树是否为BST树(二叉搜索树)

分析: 对于每个结点,需要检查其左子树中的最大值是否小于当前结点的值,且右子树中的最小值是否大于当前结点的值 而我们知道对于一棵二叉树搜索树来说,其每一棵子树也都是二叉搜索树,且其最小值为最左边的结点,最大值为最右边的结点。 所以反过来讲,就是如果一棵普通二叉树的任意一棵左子树中的最大值(左子树的最右边结点)大于等于当前根结点或者任意一棵右子树的最小值(右子树的最左边结点)小于当前根结点,那么这...

无意呢的博客 1993

【数据结构】-二叉搜索树(BST)

如图所示,二叉搜索树(binary search tree)满足以下条件。对于根节点,左子树中所有节点的值 < 根节点的值 < 右子树中所有节点的值。任意节点的左、右子树也是二叉搜索树,即同样满足条件1.。二分搜索树有着高效的插入、删除、查询操作。平均时间的时间复杂度为 O(log n),最差情况为 O(n)。二分搜索树与堆不同,不一定是完全二叉树,底层不容易直接用数组表示故采用链表来实现二分搜索树。只有在高频添加、低频查找删除数据的场景下,数组比二叉搜索树的效率更高。查找元素插入元素。

knoci的博客 5692

[数据结构] python 二叉搜索树(BST树)的插入

一、概念 二叉搜索树(Binary Search Tree)是一颗二叉树且满足性质:设x是二叉树的一个节点。如果y树x左子树的一个节点,那么;如果y是x右子树的一个节点,那么。 用通俗一点的话来说就是在一棵二叉树中,左子树所有节点都比它的根节点小,右子树所有节点都比它的根节点大。(如图所示) 所以当我们要定义一个BST树时,用双链表来做就要想到要初始化的东西: 1. 数据域data 0 2. 树的左孩子和右孩子(lchild/rchild) 3. 他们的双亲parent 定义BST树代码.

qq_51148692的博客 1651

【数据结构】二叉搜索树(BST树)的定义、构建、插入、删除及查找操作

一、概念 二叉搜索树(BST树):又叫二叉排序树,二叉查找树。它或者是一棵空树;或者是具有以下性质的二叉树: 1.每个结点都有一个数据域,且所有节点的数据域互不相同; 2.若它的左子树不为空,则左子树上的所有结点的值都小于根节点的值; 3.若它的右子树不为空,则右子树上的所有节点的值都大于根节点的值; 4.左子树和右子树都是二搜索树。 对二叉搜索树...

PinkBananA_的博客 2908

数据结构 第七章 二叉搜索树(BST BBST AVL树)

数据结构 第七章 二叉搜索树概述平衡二叉树BSTBST:查找BST:删除BST:平衡与等价AVL树 概述 词条(结点)由Key和Value构成,且Key可以比较大小 顺序性:任一结点均不小于其左孩子,不大于其右孩子(此处包括了左右孩子的所有子结点) 单调性:BST的中序遍历必然单调非降,树根结点的左侧子结点必然在遍历中根结点的左侧,右子结点在根结点右侧,所有结点的投影即为BST的中序遍历 平衡二叉树BST BST:查找 因为BST是有序的,所以查找结点e即与根结点v比较,如果e小于v则进入左子树,再与左子

CptOctopus的博客 442

STM32CUBEMX | STM32L431RCT6的内部Flash操作

一、STM32CUBEMX配置 1、选择芯片型号: 2、配置时钟源 1、 如果选择使用外部高速时钟(HSE),则需要在System Core中配置RCC; 2、 如果使用默认内部时钟(HSI),这一步可以略过; 3、配置时钟树 STM32L4的最高主频到80M,所以配置PLL,最后使HCLK = 80Mhz即可: 4、代码生成设置 点击GENERATE CODE即可生成MDK-V5工程: 二、在MDK中编写、编译、下载用户代码 1、STM32内部Flash及HAL库API 查看所使用芯片的信息,

yongridada的博客 5570

数据结构中常见的树(BST二叉搜索树、AVL平衡二叉树、RBT红黑树、B-树、B+树、B*树)

BST树        即二叉搜索树:        1.所有非叶子结点至多拥有两个儿子(Left和Right);        2.所有结点存储一个关键字;        3.非叶子结点的左指针指向小于其关键字的子树,右指针指向大于其关键字的子树;        如:                BST树的搜索,从根结点开始,如果查询的关键字与结点的关键字相等,那么就命中; ...

军爸爸的博客 254

在MATLAB产生正态(Gauss)分布随机数

在 MATLAB 中内置了有产生标准正态(Gauss)分布的随机数函数,使用方法如下: 其中 为产生矩阵的行数和列数, 为产生矩阵的个数,产生的矩阵中的每个元素均为服从 N(0,1)N(0, 1)N(0,1) 的标准正态分布的元素。使用如下命令产生一个 的服从的随机数矩阵: 绘制图像效果如下: 可以看到这里随机数服从 的标准正态分布。假设 X∼N(0,1)X\sim N(0,1)X∼N(0,1),则 3X+33X+33X+3 服从 N(3,9)N(3,9)N(3,9) 分布,因此我们要产生服从 N(

程序必须为人类阅读而编写,并且仅仅碰巧可以让机器执行 3万+

ABB机器人C#二次开发实战:从通信打通到数据读写的落地指南(附完整工程)

最近在做自动化产线升级项目时,遇到一个核心需求:用C#上位机实时读取ABB机器人的关节角度、IO信号,同时下发运动指令和参数配置。翻遍全网,要么是Robot Studio的基础操作教程,要么是C++/VC++的老旧案例,C#相关的实操内容要么只给片段代码,要么跳过通信配置、权限设置等关键步骤,导致刚上手时踩了无数坑——连接超时、数据读不到、写入无响应,甚至误触发机器人安全保护。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1400

【Java数据结构】BST树(二叉搜索树)总结03(求BST树高度,求BST树节点个数)

二叉树总结:入口 二叉树的基本操作: 1、插入,删除 操作 2、前、中、后序遍历,层序遍历 3、求BST树高度,求BST树节点个数 4、返回中序遍历第k个节点的值 5、判断一个二叉树是否是BST树,判断一个BST树是否是AVl树 6、BST树的镜像 7、把BST树满足[begin,end]区间的值放在集合中、打印出来 8、判断是否是子树 9、按层打印二叉树 1、求BST...

懂技术的猫 2224

通过两个mark点确定某一个点的位置

read_image (Image0, '0.bmp') binary_threshold (Image0, Region, 'max_separability', 'dark', UsedThreshold) connection (Region, ConnectedRegions) fill_up (ConnectedRegions, RegionFillUp) select_shape_std (RegionFillUp, SelectedRegions, 'max_area', 70) red...

优快云博客 3890

数据结构之 二叉搜索树、二叉排序树、BST树

二叉搜索树 BST 二叉搜索树简称BST树 二叉搜素树是二叉树的一种,数组这种数据结构也能够实现对元素的快速查找,但是对于元素的添加、删除和更新操作,使用数组来实现的话,就会存在较高的时间复杂度(O(n))级别。对于添加、删除、查找操作若是要保持较低的时间复杂度可以采用二叉搜索树来实现。 二叉搜索树又称二叉排序树,其节点之间按照一定的顺序进行排放可以极大地提高查找的效率,由于是树形结构,其在添加和删除操作上面的操作不像数组一样需要进行元素的复制。 建立一个BST树的过程,首先添加的是根部节点,然后新添加

cyt 381

QuickFix Java 讲解(五)消息的收发与查看

本系列力求手把手教你怎样利用QuickFix Java 搭建自己的 FIX 协议收发平台,以及其中的注意事项。 所有源码的地址(免费): https://github.com/zongzhec/QuickFixPractise 这节我们讨论将Acceptor和Initiator启动以后,收到的消息极其查看方式。 6. 收发双方的通信 6.1. 启动后的通信和登录 为方便起见,这里我们使用统一的源码:https://github.com/zongzhec/QuickFixPractise ..

2249

RK3576平台Buildroot嵌入式Linux镜像构建实战

嵌入式Linux镜像构建是连接硬件能力与软件功能的核心技术环节,其本质是基于目标SoC架构的交叉编译、内核定制与根文件系统集成过程。原理上依赖工具链适配、设备树绑定、分区镜像生成等关键步骤,技术价值在于实现轻量、确定、可复现的系统交付。典型应用场景涵盖ARM64开发板(如RK3576)、工业边缘网关及国产化信创终端。本文以TaishanPi-3为载体,深入解析Buildroot在RK3576平台上的配置裁剪、并行编译优化、genimage分区合成及update.img烧录准备,覆盖从环境选型(Ubuntu

weixin_36047538的博客 141

【Java数据结构】BST树(二叉搜索树)总结06(求BST树的镜像)

二叉树总结:入口 二叉树的基本操作: 1、插入,删除 操作 2、前、中、后序遍历,层序遍历 3、求BST树高度,求BST树节点个数 4、返回中序遍历第k个节点的值 5、判断一个二叉树是否是BST树,判断一个BST树是否是AVl树 6、BST树的镜像 7、把BST树满足[begin,end]区间的值放在集合中、打印出来 8、判断是否是子树 9、按层打印二叉树 BST树的镜像 ...

懂技术的猫 251

RK3588部署实战:利用RGA硬件加速单元优化YOLOv5的图像预处理与推理性能

摘要:本文探讨了在Rockchip芯片上使用RGA(Rockchip图形加速器)实现YOLOv5图像预处理的过程。通过对比RGA和OpenCV两种方式处理图像的速度,发现RGA加速效果不明显且不稳定(13-17fps),分析原因可能是图片尺寸过小和内存操作消耗时间。文章详细介绍了RGA版本的resize和letterbox实现代码,包括图像缩放、边缘填充等功能,并提供了预处理流程和性能监控方法。结果表明在当前场景下RGA尚未达到预期加速效果,可能与官方代码下架和实现细节有关。

know_F0727的博客 294

【Java数据结构】BST树(二叉搜索树)总结05(判断二叉树是否是BST树,AVL树)

二叉树总结:入口 二叉树的基本操作: 1、插入,删除 操作 2、前、中、后序遍历,层序遍历 3、求BST树高度,求BST树节点个数 4、返回中序遍历第k个节点的值 5、判断一个二叉树是否是BST树,判断一个BST树是否是AVl树 6、BST树的镜像 7、把BST树满足[begin,end]区间的值放在集合中、打印出来 8、判断是否是子树 9、按层打印二叉树 1、判断是否...

懂技术的猫 708

【教培管家】小程序实战(五):体验课预约——从流量到转化的闭环

本节我们通过变量状态管理和数据联动,实现了孩子选择和日期选定。下一篇我们继续讲解预约页面,根据选择的日期来筛选排课,供用户进行预约。

低代码布道师的博客 1563

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

数据结构中常见的树(BST二叉搜索树、AVL平衡二叉树、RBT红黑树、B-树、B+树、B*树)(转)...

原文链接:数据结构中常见的树(BST二叉搜索树、AVL平衡二叉树、RBT红黑树、B-树、B+树、B*树) BST树        即二叉搜索树:        1.所有非叶子结点至多拥有两个儿子(Left和Right);        2.所有结点存储一个关键字;        3.非叶子结点的左指针指向小于其关键字的子树,右指针指向大于其关键字的子树;        如:     ...

weixin_33806914的博客 95

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

算法学习笔记——数据结构:二叉搜索树BST、AVL树、伸展树、B树、B+树

二叉搜索树BST 二叉搜索树BST,即BinarySearchTree,其特性是: 对于任意节点,如果其值为val,则左子树所有节点值小于等于val,且右子树所有节点值大于等于val 注意利用此特性,避免多余的访问 def traverseBST(node: TreeNode, target: int): """BST遍历框架""" if node is None: return if node.val == target:

Insomnia_X的博客 493

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 【数据结构基础】树 - 基础和Overview
下一篇: 【数据结构基础】树 - 平衡二叉树(AVL)
毕设王同学
博客等级 码龄12年 133粉丝 128原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

毕设王同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值