文章目录
  1. 1. Sum Root to Leaf Numbers
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

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   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.

思路

DFS dfs(root,root->val)

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

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

python 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
# @param {TreeNode} root
# @return {integer}
def __init__(self):
self.sum=0

def sumNumbers(self, root):
if None == root:
return 0
self.dfs(root, root.val)
return self.sum

def dfs(self, root, val):
if not root.left and not root.right:
self.sum += val
if None != root.left:
self.dfs(root.left, val * 10 + root.left.val)
if None != root.right:
self.dfs(root.right, val * 10 + root.right.val)

文章目录
  1. 1. Sum Root to Leaf Numbers
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题