• LeetCode: Path Sum II


    多数次过

     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 sum, vector<vector<int>> &ret, vector<int> &tmp) {
    13         if (!root) return;
    14         tmp.push_back(root->val);
    15         if (sum == root->val && !root->left && !root->right) ret.push_back(tmp);
    16         if (root->left) dfs(root->left, sum-root->val, ret, tmp);
    17         if (root->right) dfs(root->right, sum-root->val, ret, tmp);
    18         tmp.pop_back();
    19     }
    20     vector<vector<int> > pathSum(TreeNode *root, int sum) {
    21         // Start typing your C/C++ solution below
    22         // DO NOT write int main() function
    23         vector<vector<int>> ret;
    24         vector<int> tmp;
    25         dfs(root, sum, ret, tmp);
    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 List<List<int>> PathSum(TreeNode root, int sum) {
    12         List<List<int>> ans = new List<List<int>>();
    13         List<int> tmp = new List<int>();
    14         dfs(root, sum, ref ans, ref tmp);
    15         return ans;
    16     }
    17     public void dfs(TreeNode root, int sum, ref List<List<int>> ans, ref List<int> tmp) {
    18         if (root == null) return;
    19         tmp.Add(root.val);
    20         if (sum == root.val && root.left == null && root.right == null) ans.Add(new List<int>(tmp.ToArray()));
    21         if (root.left != null) dfs(root.left, sum - root.val, ref ans, ref tmp);
    22         if (root.right != null) dfs(root.right, sum -  root.val, ref ans, ref tmp);
    23         tmp.RemoveAt(tmp.Count-1);
    24     }
    25 }
    View Code
  • 相关阅读:
    iOS集成ijkplayer视频直播框架,遇到的bug和坑...
    push notification获取device token
    ios xcode Code signing failed 解决方案
    ios 返回指定导航控制器
    ios git 终端提交
    mysql问题集合
    mysql 备份和恢复
    cacti 异常问题
    硬盘各项检测
    LVS DR模式(直接路由模式)
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3029889.html
Copyright © 2020-2023  润新知