第六周:[Leetcode]129. Sum Root to Leaf Numbers

来源:互联网 发布:什么软件可以下载软件 编辑:程序博客网 时间:2024/04/30 18:23

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.


DFS过程中维护一个cur变量记录该路径构成的root-to-leaf number,到叶子节点时与已有结果相加即可。


class Solution {public:    int sumNumbers(TreeNode* root) {        if(root == NULL)            return 0;        int sum = 0,cur = 0;        dfs(root,sum,cur);        return sum;    }    void dfs(TreeNode* p,int &sum,int &cur){        if(p == NULL)            return;        cur *= 10;        cur += p -> val;        if(p -> left == NULL && p -> right == NULL){            sum += cur;            cur -= p -> val;            cur /= 10;            return;        }        dfs(p -> left, sum, cur);        dfs(p -> right, sum, cur);        cur -= p -> val;        cur /= 10;    }};
0 0
原创粉丝点击