【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.

【樹的遞歸的策略】:

1. 結果在root產生,可以遵循traversal order, 一般函數遞歸返回結果

2. 結果在leaf節點產生,並難以遵循traversal order, 並且產生結果需要父節點的數據,可以設置全局變量或者變量引用,在遞歸中變量得到更新,最終返回這個變量

思路:

用遞歸的dfs計算每一層的值,但後*10往下遞歸,每次遞歸改變全局變量presum的值。

/**
 * 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 Presum;
    int sumNumbers(TreeNode *root) {
        if(!root) return 0;
        int sum=0;
        dfs(root, sum);
        return Presum;
    }
    int dfs(TreeNode *root, int sum){
        if(root==NULL) return 0;    //not a node, add 0 to the sum;
        sum = sum*10+root->val;     // the former value of the previous level will be multipled 10 and add up the new value here.
        
        if(!root->left&&!root->right) Presum +=sum; //reach the leaf, add up the sum.
        dfs(root->left, sum);
        dfs(root->right, sum);
    }
};

此處用遞歸實現的深度優先搜索。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章