• 刷题96—树(三)


    149.二叉树的所有路径

    题目链接

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-tree-paths
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题目描述

    给定一个二叉树,返回所有从根节点到叶子节点的路径。

    说明: 叶子节点是指没有子节点的节点。

    示例:

    输入:

    1
    /
    2 3

    5

    输出: ["1->2->5", "1->3"]

    解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

    题目分析

    1. 递归遍历左右子树;
    2. 当左子树和右子树都为空的时候,说明遍历到叶子节点,将路径存入数组;
    3. 非叶子节点加"->"。
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {string[]}
     */
    var binaryTreePaths = function(root) {
        let arr = [];
        if(root){
            rode(root,null);
        }
        return arr;
    
        function rode(root, link){
            let nextlink = link ? link + "->" + root.val:root.val+"";
            if(root.left == null && root.right == null) arr.push(nextlink);
            else{
                if(root.left) rode(root.left,nextlink);
                if(root.right) rode(root.right,nextlink);
            }
        }
    };
    

      

    150.从根到叶的二进制数之和

    题目链接

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题目描述

    给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。

    对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。

    以 10^9 + 7 为模,返回这些数字之和。

    示例:

     

    输入:[1,0,1,0,1,0,1]
    输出:22
    解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
     

    提示:

    树中的结点数介于 1 和 1000 之间。
    node.val 为 0 或 1 。

    题目分析

    1. 递归遍历左右子树;
    2. 当左子树和右子树都为空的时候,说明遍历到叶子节点,求和;
    3. 每一个节点上的数字转换为10进制并加到下一个节点上。
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number}
     */
    var sumRootToLeaf = function(root) {
        let sum = 0;
        if(root){
            rode(root,0);
        }
        return sum % (Math.pow(10, 9) + 7);
        function rode(root,link){
            let nextlink = link * 2 + root.val;
            if(root.left == null && root.right == null){
                sum += nextlink;
            }else{
                if(root.left) rode(root.left,nextlink);
                if(root.right) rode(root.right,nextlink);
            }
        }
    };
    

      

  • 相关阅读:
    Vijos Oct.28 NOIP2012模拟赛
    QBXT day3 圆盘自动机 游戏 方块
    QBXT day2 最近点对 最长路径 山峰
    1609: [Usaco2008 Feb]Eating Together麻烦的聚餐
    1617: [Usaco2008 Mar]River Crossing渡河问题
    委托的Lambda表达式
    值转换器IValueConverter
    Silverlight中遇到的一些问题
    匿名方法
    Silverlight中的Binding
  • 原文地址:https://www.cnblogs.com/liu-xin1995/p/12861507.html
Copyright © 2020-2023  润新知