129. Sum Root to Leaf Numbers

原创 2016年08月28日 17:08:32

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.

Subscribe to see which companies asked this question

 struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
	int sumNumbers(TreeNode* root) {
		if (root == NULL) return 0;
		sum = 0;
		dfs(root, 0);
		return sum;
	}
private:
	void dfs(TreeNode* root, int tmp){
		tmp = tmp * 10 + root->val;
		if (root->left == NULL&&root->right == NULL){
			sum += tmp;
		}
		if (root->left)
			dfs(root->left, tmp);
		if (root->right)
			dfs(root->right, tmp);
	}
	int sum;
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode:129. Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a numb...

leetcode129. Sum Root to Leaf Numbers

129. Sum Root to Leaf NumbersGiven a binary tree containing digits from 0-9 only, each root-to-leaf ...

Leetcode 129. Sum Root to Leaf Numbers (Medium) (cpp)

Leetcode 129. Sum Root to Leaf Numbers (Medium) (cpp)
  • Niko_Ke
  • Niko_Ke
  • 2016年11月24日 04:53
  • 164

[leetcode] #129 Sum Root to Leaf Numbers

1.题目 Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a...

leetcode解题之57. Binary Tree Paths&129. Sum Root to Leaf Numbers Java版 (二叉树路径)

129. Sum Root to Leaf Numbers ,257. Binary Tree Paths ,leetcode解题之129. Sum Root to Leaf Numbers Jav...

LeetCode题解-129-Sum Root to Leaf Numbers

原题 原题链接:https://leetcode.com/problems/sum-root-to-leaf-numbers/ 解法概览 解法1:迭代法,后序遍历 解法2:递归...

leetcode 129. Sum Root to Leaf Numbers-根到叶子之和|bfs|dfs|递归|非递归

原题链接:129. Sum Root to Leaf Numbers 【思路-Java】非递归实现 public class Solution { public int sumNumbers(...

LeetCode129 Sum Root to Leaf Numbers

详细见:leetcode.com/problems/sum-root-to-leaf-numbers Java Solution: github package leetcode; ...
  • zxwtry
  • zxwtry
  • 2017年05月13日 21:50
  • 149

LeetCode: Sum Root to Leaf Numbers [129]

【题目】 Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a ...

Leetcode-129. Sum Root to Leaf Numbers

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN...
  • mcf171
  • mcf171
  • 2016年10月26日 20:50
  • 88
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:129. Sum Root to Leaf Numbers
举报原因:
原因补充:

(最多只允许输入30个字)