A typical DFS usage, no big deal:
class Solution { public: int dfs(TreeNode *p, int pval) { if( !p->left && !p->right ) { int ssum = pval * 10 + p->val; return ssum; } int rl = 0, rr = 0; if(p->left) rl = dfs(p->left, pval * 10 + p->val); if(p->right) rr = dfs(p->right, pval * 10 + p->val); return rl + rr; } int sumNumbers(TreeNode *root) { int ret = 0; if(root) ret = dfs(root, 0); return ret; } };
LeetCode "Sum Root to Leaf Numbers",布布扣,bubuko.com
LeetCode "Sum Root to Leaf Numbers"
原文地址:http://www.cnblogs.com/tonix/p/3850102.html