【LeetCode】Sum Root to Leaf Numbers 解题报告
2014-09-22 17:14
357 查看
【题目】
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 =
【思路】
二叉树的穷尽搜索,递归法即可。
【Java代码】
Given a binary tree containing digits from
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.
【思路】
二叉树的穷尽搜索,递归法即可。
【Java代码】
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { int sum = 0; public int sumNumbers(TreeNode root) { if (root == null) return 0; run(root, 0); return sum; } public void run(TreeNode root, int num) { num = 10 * num + root.val; if (root.left == null && root.right == null) { sum += num; } if (root.left != null) { run(root.left, num); } if (root.right != null) { run(root.right, num); } } }
相关文章推荐
- LeetCode解题报告—— Sum Root to Leaf Numbers & Surrounded Regions & Single Number II
- Leetcode 129. Sum Root to Leaf Numbers 计算路径和 解题报告
- 【LeetCode】129. Sum Root to Leaf Numbers 解题报告(Python)
- leetcode解题报告:129. Sum Root to Leaf Numbers
- [Leetcode] 129. Sum Root to Leaf Numbers 解题报告
- LeetCode 129. Sum Root to Leaf Numbers 解题报告
- [leetcode] 129. Sum Root to Leaf Numbers 解题报告
- 【leetcode】Sum Root to Leaf Numbers
- leetcode: Sum Root to Leaf Numbers
- [Leetcode]Sum Root to Leaf Numbers
- leetcode之Sum Root to Leaf Numbers
- leetcode:Sum Root to Leaf Numbers
- leetcode Sum Root to Leaf Numbers(所有路径之和)
- [LEETCODE] Sum Root to Leaf Numbers
- [LeetCode] Sum root to leaf numbers
- LeetCode之sum root to leaf numbers
- [leetcode] Sum Root to Leaf Numbers
- [LeetCode] Sum Root to Leaf Numbers, Solution
- leetcode -- Sum Root to Leaf Numbers
- LeetCode 129: Sum Root to Leaf Numbers