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

分析:直接从根节点开始采取深度优先遍历得到所有的数值结果,可以有递归和非递归两种版本。

非递归:

/**
 * 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) {
    int sum = 0;
    if(root == NULL) return sum;
    stack<TreeNode *> array;
    stack<int> val;
    array.push(root);
    val.push(0);
    while(!array.empty()){
        TreeNode *node = array.top();
        int prev = val.top();
        array.pop();
        val.pop();
        while(node->left != NULL){
            int cur = prev*10 + node->val;
            if(node->right != NULL){
                array.push(node->right);
                val.push(cur);
            }
            prev = cur;
            node = node->left;
        }
        int cur = prev*10 + node->val;
        if(node->right == NULL){
            sum += cur;
        }else{
            array.push(node->right);
            val.push(cur);
        }
    }
    return sum;
    }
};

递归:

/**
 * 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 dfs(root, 0);
    }
    
private:
    int dfs(TreeNode *root, int sum) {
        if (root == nullptr) return 0;
        if (root->left == nullptr && root->right == nullptr)
            return sum * 10 + root->val;
        return dfs(root->left, sum * 10 + root->val) + dfs(root->right, sum * 10 + root->val);
    }
};


你可能感兴趣的:(【Leetcode】Sum Root to Leaf Numbers)