LeetCode: Sum Root to Leaf Numbers

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   strong   for   ar   div   

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 };

 

LeetCode: Sum Root to Leaf Numbers

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.