zoukankan      html  css  js  c++  java
  • Sum Root to Leaf Numbers

    Sum Root to Leaf Numbers

    问题:

    Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

    An example is the root-to-leaf path 1->2->3 which represents the number 123.

    思路:

      dfs

    我的代码:

    public class Solution {
        public int sumNumbers(TreeNode root) {
            if(root == null) return 0;
            List<String> list = new ArrayList<String>();
            dfs(list, "", root);
            int sum = 0;
            for(String s : list)
            {
                sum += Integer.valueOf(s);
            }
            return sum;
        }
        public void dfs(List<String> list, String s, TreeNode root)
        {
            if(root == null)
                return;
            if(root.left == null && root.right == null)
            {
                list.add(s+root.val);
                return;
            }
            int val = root.val;
            dfs(list, s + val, root.left);
            dfs(list, s + val, root.right);
        }
    }
    View Code

    他人代码:

    public class Solution {
        public int sumNumbers(TreeNode root) {
            return dfs(root, 0);
        }
    
        private int dfs(TreeNode root, int prev){
            if(root == null) {
                return 0;
            }
    
            int sum = root.val + prev * 10;
            if(root.left == null && root.right == null) {
                return sum;
            }
    
            return dfs(root.left, sum) + dfs(root.right, sum);
        }
    }
    View Code

    学习之处:

    • 他人代码里面通过记录prev,进行数值的串联,一来省去了List的存储空间,二来不用Integer To String了
  • 相关阅读:
    ent 基本使用十二 字段
    ent 基本使用十一 sql.DB 集成
    ent 基本使用十 数据库迁移
    ent 基本使用九 代码生成
    ent 基本使用八 索引
    ent 基本使用七 Config
    ent 基本使用六 Mixin
    ent 基本使用五 schema介绍
    ent 基本使用四 图遍历查询
    ent 基本使用 三 边(关系处理)
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4330017.html
Copyright © 2011-2022 走看看