C++ 练习题

From 牛客网 Leetcode 练习题;

[编程题] sum-root-to-leaf-numbers

时间限制:1秒

空间限制:32768K


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.

 

/**
 * Definition for binary tree
 * 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;
        if (root->left==NULL && root->right == NULL)
            return root->val;
        else
            return sumRoots(root,0);
    }
    
    int sumRoots(TreeNode *root, int val){
    if (root == NULL)
        return 0;
    val = val*10+root->val;
    if (root->left==NULL && root->right == NULL)
        return val;
    else
        return sumRoots(root->left,val)+sumRoots(root->right,val);
}
};

 

上一篇:自己整理的机器学习算法应用指南


下一篇:LeetCode 742. Closest Leaf in a Binary Tree