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了

你可能感兴趣的:(number)