LeetCode練習-中等卷

木頂思上發表於2016-09-11

題目連結: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],
]

分析回溯法





相關文章