leetcode Sum Root to Leaf Numbers

Sum Root to Leaf Numbers

  Total Accepted: 20961  Total Submissions: 70322 My Submissions

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.

Have you been asked this question in an interview?  Yes

Discuss


这道题目,用递归就可以完成。

1.一直向子树递归,并存储路径节点上的信息,如果遇到叶子节点,把路径上所有的数字转换成一个数,并加到最终的和当中

2.感觉用层次遍历也可以实现,如果走到叶子节点,就把其值加到总和当中。


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 //7:20 
class Solution {
public:
    int res = 0;
    int sumNumbers(TreeNode *root) {
        if(root==NULL)
        {
            return res;
        }
        vector<int> nums;
        nums.push_back(root->val);
        dfs(root,nums);
        return res;
    }
    void dfs(TreeNode *r,vector<int> &nums)
    {
        int sum = 0,pow = 1;
        if(r->left==NULL && r->right==NULL)
        {
            for(int i=nums.size()-1;i>=0;i--)
            {
                sum += nums[i]*pow;
                pow *= 10;
            }
            res += sum;
            return ;
        }
            if(r->left!=NULL)
            {
                nums.push_back(r->left->val);
                dfs(r->left,nums);
                nums.pop_back();
            }
                if(r->right!=NULL)
            {
                nums.push_back(r->right->val);
                dfs(r->right,nums);
                nums.pop_back();
            }
        return ;
    }
};


你可能感兴趣的:(递归,树的遍历)