Django-Multitenant,分散式多租戶資料庫專案實戰(Python/Django+Postgres+Citus)
阿新 • • 發佈:2022-03-19
113. 路徑總和 II
給你二叉樹的根節點root
和一個整數目標和 targetSum
,找出所有 從根節點到葉子節點 路徑總和等於給定目標和的路徑。
葉子節點 是指沒有子節點的節點。
示例 1:
輸入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 輸出:[[5,4,11,2],[5,8,4,5]]
示例 2:
輸入:root = [1,2,3], targetSum = 5 輸出:[]
示例 3:
輸入:root = [1,2], targetSum = 0 輸出:[]
提示:
- 樹中節點總數在範圍
[0, 5000]
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
1 #include <iostream> 2 #include <vector> 3 4 using namespace std; 5 6 /** 7 Definition for a binary tree node. 8 */ 9 struct TreeNode { 10 int val; 11 TreeNode *left; 12 TreeNode *right; 13 TreeNode() : val(0), left(nullptr), right(nullptr) {} 14 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 15 TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 16 }; 17 18 class Solution { 19 public: 20 void pathSumHelper(TreeNode *node, int sum, vector<int> path, vector<vector<int>> &answer) { 21 if (node == nullptr) { 22 return; 23 } 24 path.push_back(node->val); 25 sum -= node->val; 26 // 當到達葉子節點且剩餘節點總和為0時,該路徑符合條件 27 if (sum == 0 && node->left == nullptr && node->right == nullptr) { 28 answer.push_back(path); 29 } 30 pathSumHelper(node->left, sum, path, answer); 31 pathSumHelper(node->right, sum, path, answer); 32 return; 33 } 34 vector<vector<int>> pathSum(TreeNode* root, int targetSum) { 35 vector<vector<int>> answer; 36 if (root == nullptr) { 37 return answer; 38 } 39 vector<int> path; 40 pathSumHelper(root, targetSum, path, answer); 41 return answer; 42 } 43 }; 44 45 int main() 46 { 47 TreeNode node1 = TreeNode(5); 48 TreeNode node2 = TreeNode(4); 49 TreeNode node3 = TreeNode(8); 50 TreeNode node4 = TreeNode(11); 51 TreeNode node5 = TreeNode(13); 52 TreeNode node6 = TreeNode(4); 53 TreeNode node7 = TreeNode(7); 54 TreeNode node8 = TreeNode(2); 55 TreeNode node9 = TreeNode(5); 56 TreeNode node10 = TreeNode(1); 57 node1.left = &node2; 58 node1.right = &node3; 59 node2.left = &node4; 60 node3.left = &node5; 61 node3.right = &node6; 62 node4.left = &node7; 63 node4.right = &node8; 64 node6.left = &node9; 65 node6.right = &node10; 66 67 Solution *test = new Solution(); 68 vector<vector<int>> answer; 69 int targetSum = 22; 70 answer = test->pathSum(&node1, targetSum); 71 for (const auto &vec : answer) { 72 for (const auto &val : vec) { 73 cout << val << " "; 74 } 75 cout << endl; 76 } 77 system("pause"); 78 return 0; 79 }
測試結果: