• LeetCode: Sum Root to Leaf Numbers


    LeetCode: Sum Root to Leaf Numbers

    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.

    地址:https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/

    算法:用递归的方法完成的。首先分别计算左右子树的和,并且把子树中所有叶子节点的深度记录下来,然后根的和=左子树的和+右子树的和+根的值*pow10(叶子节点的深度)。代码:

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int sumNumbers(TreeNode *root) {
    13         vector<int> level;
    14         if(!root)   return 0;
    15         return sum(root,level);
    16     }
    17     int sum(TreeNode *root, vector<int> &level){
    18         if(!root)   return -1;
    19         if(!root->left && !root->right){
    20             level.push_back(1);
    21             return root->val;
    22         }
    23         vector<int> left;
    24         int left_sum = sum(root->left,left);
    25         vector<int> right;
    26         int right_sum = sum(root->right,right);
    27         int total_sum = 0;
    28         if(left_sum >= 0){
    29             total_sum += left_sum;
    30             vector<int>::iterator it = left.begin();
    31             for(; it != left.end(); ++it){
    32                 total_sum += (root->val * int(pow10(*it)));
    33                 level.push_back(*it + 1);
    34             }
    35         }
    36         if(right_sum >= 0){
    37             total_sum += right_sum;
    38             vector<int>::iterator it = right.begin();
    39             for(; it != right.end(); ++it){
    40                 total_sum += (root->val * int(pow10(*it)));
    41                 level.push_back(*it + 1);
    42             }
    43         }
    44         return total_sum;
    45     }
    46 };
  • 相关阅读:
    React.render和reactDom.render的区别
    CSS中position的4种定位详解
    React.js入门必须知道的那些事
    JS处理事件小技巧
    React.js深入学习详细解析
    React.js实现原生js拖拽效果及思考
    Linux ./configure && make && make install 编译安装和卸载
    Redis set集合结构及命令详解
    Redis数据过期策略
    Redis TTL命令
  • 原文地址:https://www.cnblogs.com/boostable/p/leetcode_sum_root_to_leaf_numbers.html
Copyright © 2020-2023  润新知