本文主要是介绍leetcode-129 Sum Root to Leaf Numbers,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
DFS的题目好像都是用递归
遇到递归的时候,把终止条件,各种条件想清楚就可以大胆写了,可以先举几个简单的例子帮助
<span style="font-family:Microsoft YaHei;font-size:14px;">/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:int sumNumbers(TreeNode *root) {if(root == NULL) return 0;int sum = 0;return helper(root,sum);}int helper(TreeNode *node,int sum){if(node->left == NULL && node->right == NULL)return sum * 10 + node->val;int val = 0;if(node->left != NULL)val += helper(node->left,sum * 10 + node->val);if(node->right != NULL)val += helper(node->right,sum * 10 + node->val);return val;}
};</span>
这篇关于leetcode-129 Sum Root to Leaf Numbers的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!