LeetCode(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,
题目
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.

分析

按照二叉树的深度遍历,累计所有路径组成整数的和。

使用二叉树的递归深度优先遍历实现!

AC代码

/** * Definition for a binary tree node. * 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 ret = 0;
        if (!root)
            return ret;
        else if (!root->left && !root->right)
        {
            ret = root->val;
            return ret;
        }
        else
            dfs(root, root->val , ret);

        return ret;
    }

    //深度优先遍历,得到所有根节点到叶子节点的路径和
    void dfs(TreeNode *root, int val, int &sum)
    {
        if (!root->left && !root->right)
            sum += val;
        if (root->left)
        {
            dfs(root->left, val * 10 + root->left->val, sum);
        }

        if (root->right)
        {
            dfs(root->right, val * 10 + root->right->val, sum);
        }
    }
};

GitHub测试程序源码

你可能感兴趣的:(LeetCode(129) Sum Root to Leaf Numbers)