• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Sum Root to Leaf Numbers

少数次过

 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 }
View Code

 

posted @ 2013-04-21 17:38  ying_vincent  阅读(132)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3