二叉树(3)

【LeetCode 困难 树 python3】145. 二叉树的后序遍历 想要看更加舒服的排版、更加准时的推送 关注公众号“不太灵光的程序员” 每日八点有干货推送,微信随时解答你的疑问 145. 二叉树的后序遍历 python3 困难 树 给定一个二叉树,返回它的 后序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? from typing import List # Definition for a binary tree node.. 阅读详情

一、判断是不是完全二叉树

给定一个二叉树,确定他是否是一个完全二叉树。

完全二叉树的定义:若二叉树的深度为 h,除第 h 层外,其它各层的结点数都达到最大个数,第 h 层所有的叶子结点都连续集中在最左边,这就是完全二叉树。(第 h 层可能包含 [1~2h] 个节点)

数据范围:节点数满足 1≤n≤100

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    public boolean isCompleteTree (TreeNode root) {
        // LinkedList支持存null而ArrayDeque不支持
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode poll = queue.poll();
            if (poll == null) {
                break;
            }
            queue.offer(poll.left);
            queue.offer(poll.right);
        }
        while (!queue.isEmpty()) {
            if (queue.poll() != null) {
                return false;
            }
        }
        return true;
    }
}

运行结果

二、判断是不是平衡二叉树

输入一棵节点数为 n 二叉树,判断该二叉树是否是平衡二叉树。

在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {

    private boolean res = true;

    public boolean IsBalanced_Solution (TreeNode pRoot) {
        res = true;
        dfs(pRoot);
        return res;
    }

    private int dfs(TreeNode root) {
        if (root == null || !res) return 0;
        int lH = dfs(root.left), rH = dfs(root.right);
        if (Math.abs(lH - rH) > 1) {
            res = false;
            return 0;
        }
        return Math.max(lH, rH) + 1;
    }

}

运行结果

三、二叉搜索树的最近公共祖先

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

1.对于该题的最近的公共祖先定义:对于有根树T的两个节点p、q,最近公共祖先LCA(T,p,q)表示一个节点x,满足x是p和q的祖先且x的深度尽可能大。在这里,一个节点也可以是它自己的祖先.

2.二叉搜索树是若它的左子树不空,则左子树上所有节点的值均小于它的根节点的值; 若它的右子树不空,则右子树上所有节点的值均大于它的根节点的值

3.所有节点的值都是唯一的。

4.p、q 为不同节点且均存在于给定的二叉搜索树中。

数据范围:

3<=节点总数<=10000

0<=节点值<=10000

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param root TreeNode类
     * @param p    int整型
     * @param q    int整型
     * @return int整型
     */
    public int lowestCommonAncestor(TreeNode root, int p, int q) {
        // write code here
        while (root.val != p && root.val != q) {
            if (p < root.val && q < root.val) {
                root = root.left;
            } else if (p > root.val && q > root.val) {
                root = root.right;
            } else {
                // 如果两个节点在这里产生了分歧, 那么这里就是最近公共祖先
                return root.val;
            }
        }
        // 其中一个节点值等于root.val, 那么root.val就是最近公共祖先
        return root.val;
    }
}

运行结果

四、在二叉树中找到两个节点的最近公共祖先

给定一棵二叉树(保证非空)以及这棵树上的两个节点对应的val值 o1 和 o2,请找到 o1 和 o2 的最近公共祖先节点。

数据范围:树上节点数满足 1≤n≤105 , 节点值val满足区间 [0,n)

要求:时间复杂度 O(n)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

/**
 * NC102 在二叉树中找到两个节点的最近公共祖先
 * @author d3y1
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @param o1 int整型
     * @param o2 int整型
     * @return int整型
     */
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        // return solution1(root, o1, o2);
        // return solution11(root, o1, o2);
        // return solution2(root, o1, o2);
        return solution22(root, o1, o2);
    }

    /**
     * 层序遍历
     * @param root
     * @param o1
     * @param o2
     * @return
     */
    private int solution1(TreeNode root, int o1, int o2) {
        Queue<QueueNode> queue = new LinkedList<>();
        queue.offer(new QueueNode(root, null));

        ArrayList<Integer> list1 = new ArrayList<>();
        ArrayList<Integer> list2 = new ArrayList<>();

        QueueNode qNode, currNode;
        TreeNode tNode;
        while (!queue.isEmpty()) {
            qNode = queue.poll();
            tNode = qNode.treeNode;

            if (tNode.val == o1) {
                list1.add(o1);
                currNode = qNode;
                while (currNode.parent != null) {
                    currNode = currNode.parent;
                    list1.add(currNode.treeNode.val);
                }
            }
            if (tNode.val == o2) {
                list2.add(o2);
                currNode = qNode;
                while (currNode.parent != null) {
                    currNode = currNode.parent;
                    list2.add(currNode.treeNode.val);
                }
            }

            if (tNode.left != null) {
                queue.offer(new QueueNode(tNode.left, qNode));
            }
            if (tNode.right != null) {
                queue.offer(new QueueNode(tNode.right, qNode));
            }
        }

        if (list1.contains(o2)) {
            return o2;
        }
        if (list2.contains(o1)) {
            return o1;
        }
        for (int val : list1) {
            if (list2.contains(val)) {
                return val;
            }
        }

        return -1;
    }

    private class QueueNode {
        TreeNode treeNode = null;
        QueueNode parent = null;
        public QueueNode(TreeNode treeNode, QueueNode parent) {
            this.treeNode = treeNode;
            this.parent = parent;
        }
    }

    //-----------------------------------------//

    /**
     * 层序遍历: 简化
     * @param root
     * @param o1
     * @param o2
     * @return
     */
    private int solution11(TreeNode root, int o1, int o2) {
        HashMap<Integer, Integer> parentMap = new HashMap<>();
        Queue<TreeNode> queue = new LinkedList<>();

        parentMap.put(root.val, -1);
        queue.offer(root);

        TreeNode tNode;
        // o1 o2 都找到 -> 结束循环
        while (!parentMap.containsKey(o1) || !parentMap.containsKey(o2)) {
            if (!queue.isEmpty()) {
                tNode = queue.poll();
                if (tNode.left != null) {
                    queue.offer(tNode.left);
                    parentMap.put(tNode.left.val, tNode.val);
                }
                if (tNode.right != null) {
                    queue.offer(tNode.right);
                    parentMap.put(tNode.right.val, tNode.val);
                }
            }
        }

        HashSet<Integer> ancestorSet = new HashSet<>();
        int val1 = o1;
        while (parentMap.containsKey(val1)) {
            ancestorSet.add(val1);
            val1 = parentMap.get(val1);
        }

        int val2 = o2;
        while (!ancestorSet.contains(val2)) {
            val2 = parentMap.get(val2);
        }

        return val2;
    }

    //-------------------------------------------//

    /**
     * 后序遍历
     * @param root
     * @param o1
     * @param o2
     * @return
     */
    private int solution2(TreeNode root, int o1, int o2) {
        return postOrder(root, o1, o2).val;
    }

    private TreeNode postOrder(TreeNode root, int o1, int o2) {
        if (root == null || root.val == o1 || root.val == o2) {
            return root;
        }

        TreeNode left = postOrder(root.left, o1, o2);
        TreeNode right = postOrder(root.right, o1, o2);

        // 左子树 未找到
        if (left == null) {
            return right;
        }
        // 右子树 未找到
        if (right == null) {
            return left;
        }

        // 一在左 一在右
        return root;
    }

    //-----------------------------------------------------//

    /**
     * 后序遍历
     * @param root
     * @param o1
     * @param o2
     * @return
     */
    private int solution22(TreeNode root, int o1, int o2) {
        return postorder(root, o1, o2);
    }

    private int postorder(TreeNode root, int o1, int o2) {
        if (root == null) {
            return -1;
        }
        if (root.val == o1 || root.val == o2) {
            return root.val;
        }

        int left = postorder(root.left, o1, o2);
        int right = postorder(root.right, o1, o2);

        // 左子树 未找到
        if (left == -1) {
            return right;
        }
        // 右子树 未找到
        if (right == -1) {
            return left;
        }

        // 一在左 一在右
        return root.val;
    }
}

运行结果

五、序列化二叉树

请实现两个函数,分别用来序列化和反序列化二叉树,不对序列化之后的字符串进行约束,但要求能够根据序列化之后的字符串重新构造出一棵与原二叉树相同的树。

二叉树的序列化(Serialize)是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树等遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#)
二叉树的反序列化(Deserialize)是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。

import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    String Serialize(TreeNode root) {
        StringBuilder res = new StringBuilder();
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            TreeNode poll = deque.poll();
            if (poll == null) {
                res.append("#,");
            } else {
                res.append(poll.val).append(',');
                deque.offer(poll.left);
                deque.offer(poll.right);
            }
        }
        return res.deleteCharAt(res.length() - 1).toString();
    }

    TreeNode Deserialize(String str) {
        if (str == null || str.isEmpty() || "#".equals(str)) {
            return null;
        }
        String[] strs = str.split(",");
        TreeNode res = new TreeNode(Integer.valueOf(strs[0]));
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.offer(res);
        for (int i = 2; i < strs.length; i += 2) {
            TreeNode poll = deque.poll();
            if (!"#".equals(strs[i - 1])) {
                poll.left = new TreeNode(Integer.valueOf(strs[i - 1]));
                deque.offer(poll.left);
            }
            if (!"#".equals(strs[i])) {
                poll.right = new TreeNode(Integer.valueOf(strs[i]));
                deque.offer(poll.right);
            }
        }
        return res;
    }
}

运行结果

六、重建二叉树

给定节点数为 n 的二叉树的前序遍历和中序遍历结果,请重建出该二叉树并返回它的头结点。

例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出如下图所示。

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param preOrder int整型一维数组
     * @param vinOrder int整型一维数组
     * @return TreeNode类
     */
    public TreeNode reConstructBinaryTree (int[] preOrder, int[] vinOrder) {
        return reConstructBinaryTree1(preOrder, 0, preOrder.length - 1, vinOrder, 0,
                                      vinOrder.length - 1);
    }

    public TreeNode reConstructBinaryTree1 (int[] preOrder, int s1, int e1,
                                            int[] vinOrder, int s2, int e2) {
        System.out.println(String.format("%d %d | %d %d", s1, e1, s2, e2));
        if (s1 > e1) return null;
        TreeNode node = new TreeNode(preOrder[s1]);
        int t = -999;
        for (int i = 0; i <= e2 - s2; i++) {
            if (vinOrder[s2 + i] == preOrder[s1]) {
                t = i;
                break;
            }
        }
        node.left = reConstructBinaryTree1(preOrder, s1 + 1, s1 + t, vinOrder, s2,
                                           s2 + t - 1);
        node.right = reConstructBinaryTree1(preOrder, s1 + t + 1, e1, vinOrder,
                                            s2 + t + 1, e2);
        return node;
    }
}

运行结果

Python3实现二叉树指定层节点的打印 接下来,我们来看如何打印二叉树指定层的节点。首先,我们需要编写一个函数,用于遍历二叉树的每一层,并将该层的节点存储到一个列表中。该函数采用递归方式遍历二叉树,当遍历到指定层数时,它将该层的节点值存储到一个列表中,并返回该列表。先来看二叉树的定义:二叉树是一种每个节点最多只有两个子节点的树结构。一个节点可以没有子节点,但不能有多于两个子节点。接下来,我们可以编写一个主函数,用于打印指定层的节点。循环遍历该列表,并依次打印每个节点值。函数,获取指定层的节点列表,然后使用。函数,打印第一层和第二层的节点值。 阅读详情

相关推荐

python3实现二叉树的遍历与递归算法解析

python3实现二叉树的遍历与递归算法解析 1、二叉树的三种遍历方式 二叉树有三种遍历方式:先序遍历,中序遍历,后续遍历 即:先中后指的是访问根节点的顺序 eg:先序 根左右 中序 左根右 后序 左右根 遍历总体思路:将树分成最小的子树,然后按照顺序输出 1.1 先序遍历 a 先访问根节点 b 访问左节点 c 访问右节点 a(b ( d ( h ) )( e ( i ) ))( c...

人生代码 ---- 公众号 1301

053、牛客网算法面试必刷TOP101--二叉树(230507)

面试必刷TOP101–二叉树,总共有道题目。提示:以下是本篇文章正文内容层序遍历,利用队列;二叉搜索树需要利用性质,一般使用中序遍历;大多数都是采用深度优先遍历,如果需要先获得子树的信息再去计算的话,采用后序遍历;

Yora123的博客 846

【LeetCode 简单 树 python3】543. 二叉树的直径

想要看更加舒服的排版、更加准时的推送 关注公众号“不太灵光的程序员” 每日八点有干货推送,微信随时解答你的疑问 543. 二叉树的直径 python3 简单 树 示例 : 给定二叉树 1 / \ 2 3 / \ 4 5 返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。 注意:两结点之间的路径长度是以它们之间边的数目表示。 # Definition for a binary tree node. class TreeNode: .

702

【牛客网面试必刷TOP101】二叉树篇(三),2024年最新大数据开发中常见的面试题

int j = 0;//数组从0下标开始。//通过中序遍历找根。

2401_84183802的博客 755

【LeetCode 中等 树 python3】144. 二叉树的前序遍历

想要看更加舒服的排版、更加准时的推送 关注公众号“不太灵光的程序员” 每日八点有干货推送,微信随时解答你的疑问 144. 二叉树的前序遍历 python3 中等 树 迭代算法 给定一个二叉树,返回它的 前序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 前序遍历 根-左-右 from typing import List # Definition for a .

767

二叉树数据结构在D3.js中的转换及思维导图应用

D3.js是一个JavaScript库,它使得基于Web标准的文档能够被转换为复杂的数据可视化。它以其强大的数据驱动的DOM操作能力而闻名,允许开发者以数据为驱动来操作文档对象模型(DOM),创建动态的、交互式的网页。由Mike Bostock、Vegard Øye 和 Jeff Heer三位开发者共同创立,D3.js的出现,为数据可视化领域带来了一场革命,使得复杂的可视化操作不再依赖于专用的图形框架。数据绑定:D3.js将数据与文档中的元素绑定,允许开发者通过简单的数据更新来改变文档结构。

weixin_36238982的博客 1048

牛客网二叉树编程题

树的高度 #include &amp;lt;iostream&amp;gt; #include &amp;lt;vector&amp;gt; using namespace std; int main() { int n, H = 1; int f, c, h; vector&amp;lt;int&amp;gt; nodes(1000, 0); // 有效节点的高度 nodes[0] = 1; ...

beashaper_的博客 536

Codesys.运动控制修改凸轮点

通过改凸轮曲线的主从轴缩放比例或者偏置。 新建多个凸轮曲线,对CAM曲线进行切换。 程序中动态修改,仅修改中间的关键点(凸轮末点修改or凸轮曲线运行中修改)。 程序中动态修改,修改首未关键点及关键点个数,需要重新触发MC_TableSelect。 使用程序新建凸轮表代码,实现电子凸轮基本运动。 我们讲的凸轮表切换、关键点修改、程序新建电子凸轮,这些方法没有本质区别,总之都是“趁曲线不注意,把凸轮表改了。

傻响雨 6828

(牛客网)二叉树的深度

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL)

ROOM 454

S32K3 MCAL配置 【MCU、PORT、DIO】

1、s32k3时钟源可由PLL, FXOSC, FIRC, SIRC, and SXOSC五种时钟源生成,可按照手册推荐配置。目标是在在S32K344板子上点亮红色LED灯,需要配置的有MCU、PORT、DIO模块。MCU最主要的是时钟配置,要翻看芯片手册,理解时钟树。1、通用配置中,没有什么特殊需求按照demo配置就好。1、配置MC_CGM mux 0 clocks时钟。1、外部晶振配置按照实际项目原理图进行配置。1、外部晶振配置,按照实际项目配置。1、PLL时钟按照手册进行配置。

weixin_43741076的博客 3244

一种解决STM32多串口同时收发的方法

在做项目中,遇到了同时调用串口通信时程序崩溃的问题,在项目中,串口1用作调试串口,串口2用作MQTT通信串口,串口3用作下位机通信串口, 串口1重定向以后,用库函数自带的printf函数打印字符串 串口2使用自己写的u2_printf函数,即va_list这套变参宏定义后使用vsprintf函数打印字符串 串口3刚开始使用串口2一样的打印方式,程序在调试调用到串口3打印函数时直接崩溃,后续将串口3改用dma转存输出,仍然无法正常调用 多次研究以后,采用三个串口都使用重定向后的库函数自带的printf

Zxp0605的博客 8796

牛客网-重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。 二叉树一般都是递归创建,不然得写多少代码。 本题是由先序和中序重新创建一颗二叉树,首先分析递归的边界。 先序序列中的1指定是树的首节点,那么从中序序列中得...

小呼哥的博客 386

【Ragflow】9.问答为什么比搜索响应慢?从源码角度深入分析

前几天看到有群友提到一个现象:Ragflow的搜索界面的问答速度很快,但聊天界面的问答速度很慢,究竟是什么原因?在深入挖掘源码之后,逐渐发现了问题的答案。

兴趣使然的创作者 2902

Python3学习实战——创建链状二叉树

Python3学习实战,创建链状二叉树,并实现链状二叉树的创建,访问,修改结点内容,层遍历,先序遍历,中序遍历,后序遍历操作,利用递归。同时还包含一些总结,链状结构和顺序结构的小对比。

e_more_day的博客 837

拆开一个烧坏的IGBT模块,手把手教你识别过压、过流、过温的“案发现场”

本文详细解析了IGBT模块失效分析的实战技巧,通过观察铝层熔化纹路、焊锡溢出形态等物理痕迹,手把手教你识别过压、过流、过温的典型失效模式。文章提供了从基础工具包到现场快速诊断的完整流程,帮助工程师精准定位IGBT模块失效的根本原因。

weixin_30655569的博客 425

DexProtector内存态匿名段检测绕过与dex重组技术

Dex文件是Android应用的核心执行单元,其结构规范(如header_item、class_def_item、code_item)决定了运行时加载与解析的底层逻辑。DexProtector通过将dex数据拆解为多个无文件名、受保护的内存匿名段(如[anon:dp_header]、[anon:dp_code]),规避传统基于文件特征或标准加载路径的检测机制。该策略依赖Android mmap内存管理与ART虚拟机对dex结构的刚性要求,形成可被观测的布局规律。理解其内存态组织原理,结合权限/大小/命名/内

weixin_30855761的博客 689

【二叉树】实战篇3

今天带大家进行二叉树的实战篇3,学会并了解如果去修改构造一棵二叉树,并且将深度解析我们叉树数中经常用到的搜索二叉树,无论什么要二叉树结构修改,搜索二叉树的性质等等,一文带大家弄懂。本文用于记录自己的学习过程,同时向大家进行分享相关的内容。本文内容参考于代码随想录同时包含了自己的许多学习思考过程,如果有错误的地方欢迎批评指正!

走进深度学习,不仅仅只是原理,更包括详细代码解读。 1339

想发故障诊断论文?手把手教你用CWRU数据集复现第一个Baseline模型

本文提供了一份基于CWRU轴承数据集的故障诊断Baseline模型实战指南,手把手教你从数据准备到模型构建的全流程。通过详细的Python代码示例和学术级实验设计,帮助初学者快速复现第一个故障诊断模型,为发表高质量论文奠定基础。

weixin_28681255的博客 428

画出有3个节点的树和有3个结点的二叉树的所有不同的形态

画的难看了点????

weixin_43326436的博客 2万+

基于STM32L4XX、HAL库的ICM-42607-P姿态传感器驱动程序设计

/ 转换为dps(±1000dps量程)float accel_x = sensor_data.accel_x * (8.0f / 32768.0f);// 转换为g值(±8g量程)#define ICM42607_I2C_ADDR 0x68 << 1 // I2C地址(SA0=0)= 0x40) { // ICM-42607的WHO_AM_I值为0x40。// 读取传感器数据。

zhusl6688的博客 835

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Python3 关于二叉树的广度优先遍历

遍历二叉树之前我们先了解一下涉及到的知识 (1)队列 >>> import queue >>> q = queue.Queue() >>> q.put(1) >>> q.put(2) >>> q.put(3) >>> q.get() 1 >>> q.get() 2 &...

小小的博客 379

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Python3实现翻转二叉树问题

Python实现翻转二叉树问题 翻转一棵二叉树。 # 二叉树的结构如下 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 解决方案 class Solution: # 从根节点开始递归翻转其左子树和右子树 def invertTree(self,...

qq_18138105的博客 432

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

LeetCode101-对称二叉树-Python3

题目 给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 思路 递归法,关键在于 return...

王俊的博客 302

Python3 树 | 二叉树的实现 遍历二叉树 二叉排序树 查找 插入 删除

一、树 非线性结构 根在顶层 root 叶在下面 除了上面的一个根节点都叫子节点(统称为节点) 根节点是唯一一个没有入边的节点 除了根节点外每个节点都有且只有一条与其他节点相连的入边(指向该节点的边),每个节点可能有许多跳出边(从该节点指向其他节点的边) 路径:有序排列,路径是唯一的 子节点集:父节点的所有“孩子” 父节点: 兄弟节点:同一个节点的所有子节点互为兄弟节点 子树:一个父节点的某个子...

kudou1994的博客 653

二叉树2-3-4树红黑树

直接进入正题:暂时只讨论了节点的插入,节点删除还未纳入。 一、如何从数组生成一个二叉树 假设数组为:{ 30, 13, 7, 43, 23, 12, 9, 33, 42, 21, 18, 6, 3, 50 },我们不对数组排序,直接生成二叉树。 创建流程: 1.将第一数作为根节点: 2.插入13,13小于30,放在30的左边子节点。 3.插入7,7小于30,7小于1...

dianshu9815的博客 401

AS3二叉树排序法排序

从别人博客上找到一篇关于as3快速排序的代码,使用后发现在有大量相同数据的情况下,排序不可靠,容易出现堆栈溢出的现象,     突然记起看过一个C的二叉树排序法,现改成AS3版本并加以注释。 全部代码如下 private function mysort(array:Vector.,left:int,right:int):void{ var tl:int = left;v

IceFlame 1578
上一篇: 二叉树(2)
下一篇: 堆/栈/队列
w_zero_one
博客等级 码龄2年 149粉丝 68原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值