129. Sum Root to Leaf Numbers

Total Accepted: 74843  Total Submissions: 229553  Difficulty: Medium

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

Hide Tags
  Tree Depth-first Search
Show Similar Problems

分析:

前序式深度优先即可!

/**
 * 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 sumNumbers(TreeNode* root) {
        if(root==NULL)//叶子
            return 0;
        m_sum=0;    
        helpSum(root,root->val);    
        return m_sum;
    }
    void helpSum(TreeNode* node,int curVal) {
        if(node->left==NULL && node->right==NULL)//叶子即可得到当前和
        {
            m_sum+=curVal;
            return;
        }
       
        if(node->left!=NULL)
            helpSum(node->left,10*curVal+node->left->val);
        if(node->right!=NULL)    
            helpSum(node->right,10*curVal+node->right->val);   
    }
private:
    int m_sum;
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51232508

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895


你可能感兴趣的:(LeetCode,C++,算法,String,面试)