We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a57563e commit 387769fCopy full SHA for 387769f
Sum Root to Leaf Numbers.cpp
@@ -0,0 +1,32 @@
1
+/**
2
+ * Definition for binary tree
3
+ * struct TreeNode {
4
+ * int val;
5
+ * TreeNode *left;
6
+ * TreeNode *right;
7
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8
+ * };
9
+ */
10
+class Solution {
11
+public:
12
+ int ans;
13
+ void dfs(TreeNode *r,int val)
14
+ {
15
+ if (!r)return;
16
+ if (!r->left&&!r->right)
17
18
+ ans+=val;
19
+ return;
20
+ }
21
+ if (r->left)dfs(r->left,val*10+r->left->val);
22
+ if (r->right)dfs(r->right,val*10+r->right->val);
23
24
+ int sumNumbers(TreeNode *root) {
25
+ // Start typing your C/C++ solution below
26
+ // DO NOT write int main() function
27
+ if (!root)return 0;
28
+ ans=0;
29
+ dfs(root,root->val);
30
+ return ans;
31
32
+};
0 commit comments