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.

Note:A leaf is a node with no children.


给定一棵二叉树,每个根节点到叶子结点的遍历可以表示一个数字,如1->2->3可表示123。求所有遍历加起来的和。

递归。从上到下遍历,在已知正在遍历的节点root和遍历过的节点的情况下,写一个函数去计算接下来遍历的值。

eg.当遍历到root:10*x+root->val


class Solution {

public:

    int sumNumbers(TreeNode* root) {

        if(!root) return 0;

        return sumNum(root, 0);

    }

    int sumNum(TreeNode* root, int x){

        if(!root->left && !root->right){

            return 10*x + root->val;

        }

        int val = 0;

        if(root->left){

            val += sumNum(root->left, 10*x+root->val);

        }

        if(root->right){

            val += sumNum(root->right, 10*x+root->val);

        }

        return val;

    }

};

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