详细见:leetcode.com/problems/sum-root-to-leaf-numbers
Java Solution: github
package leetcode;
import java.util.LinkedList;
import java.util.Queue;
import tools.TreeNode辅助;
/*
* 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 3
The 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.
*/
import tools.TreeNode辅助.TreeNode;
public class P129_SumRoottoLeafNumbers {
public static void main(String[] args) {
TreeNode t = TreeNode辅助.A_生成满二叉树(new int[] {
1,
2, 3
});
System.out.println(new Solution1().sumNumbers(t));
System.out.println(new Solution2().sumNumbers(t));
}
static class Solution1 {
public int sumNumbers(TreeNode root) {
if (root == null) return 0;
int[] sum = {0};
search(root, 0, sum);
return sum[0];
}
private void search(TreeNode root, int val, int[] sum) {
if (root.left == null && root.right == null)
sum[0] += val * 10 + root.val;
if (root.left != null)
search(root.left, val * 10 + root.val, sum);
if (root.right != null)
search(root.right, val * 10 + root.val, sum);
}
}
static class Solution2 {
public int sumNumbers(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
Queue<Integer> v = new LinkedList<Integer>();
q.add(root);
v.add(0);
int ans = 0, t = 0;
TreeNode n = null;
while (! q.isEmpty()) {
n = q.poll();
t = v.poll();
if (n.left == null && n.right == null)
ans += t*10+n.val;
if (n.left != null) {
q.add(n.left);
v.add(t*10 + n.val);
}
if (n.right != null) {
q.add(n.right);
v.add(t*10 + n.val);
}
}
return ans;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/sum-root-to-leaf-numbers
AC 3ms 0.00%
*/
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void search(struct TreeNode* root, int * sum, int t) {
int l = 0, r = 0;
if (root == NULL) return;
t = t*10+root->val;
search(root->left, sum, t);
search(root->right, sum, t);
if (root->left == NULL && root->right == NULL)
*sum += t;
}
int sumNumbers(struct TreeNode* root) {
int sum = 0;
search(root, &sum, 0);
return sum;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/sum-root-to-leaf-numbers
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年5月13日
@details: Solution: 52ms 35.43%
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def search(self, root, val, ans):
if root.left == None and root.right == None:
ans[0] += (val * 10 + root.val)
if root.left != None:
self.search(root.left, val * 10 + root.val, ans)
if root.right != None:
self.search(root.right, val * 10 + root.val, ans)
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None: return 0
ans = [0]
self.search(root, 0, ans)
return ans