LeetCode刷題筆記(樹):sum-root-to-leaf-numbers
阿新 • • 發佈:2019-02-17
題目描述
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.
給定一個二進位制樹,只包含0-9的數字,每個根到葉的路徑可以代表一個數字。 一個例子是代表數字123的根到葉子路徑1-> 2-> 3。 找到所有根到葉子數量的總和。 例如,1 / \ 2 3根到葉子路徑1 - > 2表示數字12。 根到葉子路徑1-> 3表示數字13。 返回總和= 12 + 13 = 25。
解題思路
採用先序遍歷的思想(根左右)+數字求和的思想(每一層都比上層和*10+當前根節點的值)。
C++版程式碼實現
/**
* 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 preorder(TreeNode *root, int sum){
if(root == NULL)
return 0;
sum = sum * 10 + root->val;
if(root->left == NULL && root->right == NULL)
return sum;
return preorder(root->left, sum) + preorder(root->right, sum);
}
int sumNumbers(TreeNode *root) {
if(root == NULL)
return 0;
int sum = 0;
return preorder(root, sum);
}
};
系列教程持續釋出中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~
完的汪(∪。∪)。。。zzz