题目链接:LeetCode练习-中等卷。
1、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.
分析:先序遍历的思想(根左右)+数字求和(每一层都比上层和*10+当前根节点的值)。
<span style="font-size:18px;">/**
* 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) {
return sumdfs(root,0);
}
int sumdfs(TreeNode *root,int sum){
if(!root)
return 0;
sum = sum*10+root->val;
if(!root->left&&!root->right)
return sum;
return sumdfs(root->left,sum)+sumdfs(root->right,sum);
}
};</span>
2、Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
分析:回溯法。