leetcode129. Sum Root to Leaf Numbers

来源:互联网 发布:unity3d 中wintext 编辑:程序博客网 时间:2024/05/16 08:51

129. 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.

Find the total sum of all root-to-leaf numbers.

For example,    1   / \  2   3The root-to-leaf path 1->2 represents the number 12.The root-to-leaf path 1->3 represents the number 13.Return the sum = 12 + 13 = 25.

解法一

递归遍历每一条从根节点到叶子结点的路径,并根据路径存成对应的值,如123,把这些值放到list列表中,最后进行遍历,求和。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int sumNumbers(TreeNode root) {        List<Integer> list = new ArrayList<Integer>();        int s = 0;        if (root == null) {            return 0;        }        helper(root, s, list);        int sum = 0;        for (int i = 0; i < list.size(); i++) {            sum += list.get(i);        }        return sum;    }    public void helper(TreeNode root, int s, List<Integer> list) {        if (root == null) {            return;        }        s = s * 10 + root.val;        if (root.left == null && root.right == null) {            list.add(s);            s = (s - root.val) / 10;            return;        }        helper(root.left, s, list);        helper(root.right, s, list);        s = (s - root.val) / 10;    }}

解法二

dfs,递归,将左右子树的完整路径加起来。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int sumNumbers(TreeNode root) {        if (root == null) {            return 0;        }        return sum(root, 0);    }    public int sum(TreeNode root, int sum) {        if (root == null) {            return 0;        }        if (root.left == null && root.right == null) {            return sum * 10 + root.val;        }        return sum(root.left, sum * 10 + root.val) +                sum (root.right, sum * 10 + root.val);    }}
原创粉丝点击