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了
  • 相关阅读:
    机器学习-正则化方法
    机器学习-回归算法
    机器学习算法一
    机器学习概览
    tensorflow机器学习初接触
    tensorflow决策树初接触
    tensorflow语法
    tensorflow第一个例子简单实用
    Hyperledger Fabric 1.0架构入门
    结合《XXXX需求征集系统》分析可用性和可修改性战术
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4330017.html
Copyright © 2011-2022 走看看