少数次过
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 void dfs(TreeNode *root, int &ret, int tmp) { 13 if (!root) return; 14 if (!root->left && !root->right) ret += tmp*10+root->val; 15 else { 16 if (root->left) dfs(root->left, ret, tmp*10+root->val); 17 if (root->right) dfs(root->right, ret, tmp*10+root->val); 18 } 19 } 20 int sumNumbers(TreeNode *root) { 21 // Start typing your C/C++ solution below 22 // DO NOT write int main() function 23 if (!root) return 0; 24 int ret = 0; 25 dfs(root, ret, 0); 26 return ret; 27 } 28 };
C#
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int SumNumbers(TreeNode root) { 12 if (root == null) return 0; 13 int ans = 0; 14 dfs(root, ref ans, 0); 15 return ans; 16 } 17 public void dfs(TreeNode root, ref int ans, int tmp) { 18 if (root == null) return; 19 if (root.left == null && root.right == null) ans += tmp * 10 + root.val; 20 else { 21 if (root.left != null) dfs(root.left, ref ans, tmp * 10 + root.val); 22 if (root.right != null) dfs(root.right, ref ans, tmp * 10 + root.val); 23 } 24 } 25 }