129. Sum Root to Leaf Numbers

欢迎fork and star:Nowcoder-Repository-github

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

解析

  • 先序遍历的思想(根左右)+数字求和(每一层都比上层和*10+当前根节点的值)
  • 可以从上到下累加,直到叶子节点,然后累加!
class Solution_129 {
public:
    int dfs(TreeNode* root, int sum)
    {
        if (!root)
        {
            return;
        }
        sum = sum * 10 + root->val;
        if (root->left==NULL&&root->right==NULL)
        {
            return sum;
        }

        return dfs(root->left, sum) + dfs(root->right, sum);
    }

    int sumNumbers_ref(TreeNode* root)
    {
        if (root == NULL)
        {
            return 0;
        }
        int sum = 0;

        return dfs(root, sum); //从根节点开始
    }

    int sumNumbers(TreeNode *root) {
        if (!root)
        {
            return 0;
        }
        stack<TreeNode*> sta;
        sta.push(root);

        int ret = 0;
        TreeNode* top = 0;
        while (!sta.empty())
        {
            top = sta.top();
            sta.pop();

            if (!top->left && !top->right)
            {
                ret += top->val;
            }
            if (top->left)
            {
                top->left->val += 10 * top->val; //但是这样改变了节点的值,可以将TreeNode* 和累积和(一个变量)组成一个pair,分开处理
                sta.push(top->left);
            }
            if (top->right)
            {
                top->right->val += 10 * top->val;
                sta.push(top->right);
            }
        }
        return ret;
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8166307.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞