[LeetCode130]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.

Analysis:

Once we see this kind of problem, no matter what sum is required to output, "all root-to-leaf" phrase reminds us the classic Tree Traversal or Depth-First-Search algorithm. Then according to the specific problem, compute and store the values we need. Here in this problem, while searching deeper, add the values up (times 10 + current value), and add the sum to final result if meet the leaf node (left and right child are both NULL).

Java

public class Solution {
    int result;
	public int sumNumbers(TreeNode root) {
        result = 0;
        getSum(root, 0);
        return result;
    }
	public void getSum(TreeNode root, int path){
		if(root==null) return;
		path = path*10+root.val;
		if(root.left==null && root.right==null){
			result+=path;
			return;
		}
		getSum(root.left, path);
		getSum(root.right, path);
	}
}

c++

void sumSubpath(TreeNode* root, int &sum, int path){
    if(root == NULL) return;
    path = path*10 + root->val;
    if(root->left == NULL && root->right == NULL){
        sum += path;
        return;
    }
    sumSubpath(root->left, sum, path);
    sumSubpath(root->right, sum, path);
}
int sumNumbers(TreeNode *root) {
    int sum = 0;
    int path = 0;
    sumSubpath(root,sum,0);
    return sum;
}






你可能感兴趣的:(LeetCode,tree,binary,DFS)