转载

sum-root-to-leaf-numbers

sum-root-to-leaf-numbers

题目描述

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \   2   3

The root-to-leaf path1->2represents the number12.

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

思想

主要是树的遍历,dfs

这也考察了递归遍历时的处理

代码

class Solution {
public:
    int sumNumbers(TreeNode *root) {
        if(root == NULL) return 0;

        int res = 0, s = 0;
        dfs(root, res, s);
        return res;
    }


    void dfs(TreeNode *root, int &res, int s) {
        s += root->val;

        if(root->left != NULL) {
            s = s * 10;
            dfs(root->left, res, s);
            s = s / 10;
        }

        if(root->right != NULL) {
            s = s * 10;
            dfs(root->right, res, s);
            s = s / 10;
        }

        if(root->left == NULL && root->right == NULL) {
            res += s;
        }
        return;
    }
};
正文到此结束
本文目录