Sum Root to Leaf Numbers
2014-06-08 12:28
239 查看
Given a binary tree containing digits from
path could represent a number.
An example is the root-to-leaf path
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
The root-to-leaf path
Return the sum = 12 + 13 =
0-9only, each root-to-leaf
path could represent a number.
An example is the root-to-leaf path
1->2->3which represents the number
123.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path
1->2represents the number
12.
The root-to-leaf path
1->3represents the number
13.
Return the sum = 12 + 13 =
25.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int sumNumbers(TreeNode root) { return sum(root, 0); } int sum(TreeNode root, int value){ int res=0; if(root==null){ return 0; }else{ int subval=value*10+root.val; if((root.left!=null)||(root.right!=null)){ res=sum(root.left, subval)+sum(root.right, subval); }else{ res=subval; } return res; } } }
相关文章推荐
- [leetcode] Sum Root to Leaf Numbers
- sum-root-to-leaf-numbers
- Sum Root to Leaf Numbers
- LeetCode_Sum Root to Leaf Numbers
- LeetCode之Sum Root to Leaf Numbers
- [LeetCode] Sum Root to Leaf Numbers 求根到叶节点数字之和
- leetcode || 129、Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- [LeetCode] Sum Root to Leaf Numbers
- 95_leetcode_Sum Root to Leaf Numbers
- 【LeetCode with Python】 Sum Root to Leaf Numbers
- LeetCode OJ--Sum Root to Leaf Numbers
- leetcode[129] Sum Root to Leaf Numbers
- 【LeetCode】Sum Root to Leaf Numbers
- leetcode:Sum Root to Leaf Numbers 【Java】
- [LEETCODE] Sum Root to Leaf Numbers
- LeetCode129:Sum Root to Leaf Numbers
- leedcode做题总结,题目Sum Root to Leaf Numbers 2013/02/18
- [LeetCode] Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers