码迷,mamicode.com
首页 > 其他好文 > 详细

<LeetCode OJ> 129. Sum Root to Leaf Numbers

时间:2016-04-29 19:08:19      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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 OJ> 129. Sum Root to Leaf Numbers

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!