• 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
  • 相关阅读:
    Java通过 Scanner 类来获取用户的输入
    Java中的Calendar 类和SimpleDateFormat 类
    JAVA中字符串常见操作
    JAVA中数组Arrays类的常见用法
    Java中的compareTo()方法,compareToIgnoreCase()方法
    python常见字符串操作
    linux常见配置文件路径
    python的匿名函数
    python列表解析式,字典解析式,集合解析式和生成器
    Django admin
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3034089.html
Copyright © 2020-2023  润新知