文章出處

Question:

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

    1   / \  2   3

 

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

 

Algorithm:DFSAccepted Code:
/** * 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 res=0;    int sumNumbers(TreeNode* root) {        DFS(root,0);        return res;    }    void DFS(TreeNode* root,int sum)    {        if(root==NULL)            return;        sum=sum*10+root->val;        if(root->left==NULL && root->right==NULL)        {            res+=sum;        }        if(root->left)            DFS(root->left,sum);        if(root->right)            DFS(root->right,sum);    }};
看文倉www.kanwencang.com網友整理上傳,為您提供最全的知識大全,期待您的分享,轉載請注明出處。
歡迎轉載:http://www.kanwencang.com/bangong/20161027/10944.html

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()