• 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
  • 相关阅读:
    Redis学习-发布/订阅
    Redis学习-Sentinel
    Redis学习-复制
    Redis学习-持久化
    Redis学习-Set
    Redis学习-SortedSet
    mac下使用apktool反编译
    ImageView setImageURI图片不改变NetWorkImageView 不显示的问题
    使用SharedPreference和对象流存储对象
    解决百度云推送通知,不显示默认Notification
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3034089.html
Copyright © 2020-2023  润新知