129Sum Root to Leaf Numbers

来源:互联网 发布:守望先锋源氏cos淘宝网 编辑:程序博客网 时间:2024/06/05 01:10

题目链接:https://leetcode.com/problems/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.

解题思路:
这道题考点还是树的先序遍历
解决办法是递归。
1. 遇到非叶子结点,更新 sum 为之前路径上结点的总和 * 10 + 当前结点的值。
2. 然后向其左右孩子传递 sum 并进行递归操作。
3. 遇到叶子结点,更新完当前路径上的 sum 值后,将 sum 加到全局 sum 上。

大神的思路和我的基本相同,但是他的代码更加简洁。下面会附上大神的代码以供参考。
大神参考链接:http://blog.csdn.net/linhuanmars/article/details/22913699

代码实现:
自己的实现:

/** * 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;        List<Integer> res = new ArrayList();        res.add(0);        helper(root, 0, res);        return res.get(0);    }    void helper(TreeNode root, int sum, List<Integer> res) {        sum = sum * 10 + root.val;        if(root.left == null && root.right == null) {            res.set(0, res.get(0) + sum);            return;        }        if(root.left != null)            helper(root.left, sum, res);        if(root.right != null)            helper(root.right, sum, res);    }}
109 / 109 test cases passed.Status: AcceptedRuntime: 1 ms

大神的代码:

/** * 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) {          return helper(root,0);      }      private int helper(TreeNode root, int sum)      {          if(root == null)              return 0;          if(root.left==null && root.right==null)              return sum*10+root.val;          return helper(root.left,sum*10+root.val)+helper(root.right,sum*10+root.val);      } }
109 / 109 test cases passed.Status: AcceptedRuntime: 1 ms
0 0
原创粉丝点击