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
输出:[]
解题思路
该题与
递归法
代码(C++)
//递归 class Solution { public: void traversal(TreeNode* node, vector<int>& path, vector<vector<int>>& result, int count) { if(!node->left && !node->right) { if (count == 0) result.push_back(path); return; } if (node->left) { path.push_back(node->left->val); count -= node->left->val; traversal(node->left, path, result, count); //递归 count += node->left->val; //回溯 path.pop_back(); //回溯 } if (node->right) { path.push_back(node->right->val); count -= node->right->val; traversal(node->right, path, result, count); //递归 count += node->right->val; //回溯 path.pop_back(); //回溯 } } vector<vector<int>> pathSum(TreeNode* root, int targetSum) { vector<vector<int>> result; if (root == nullptr) return result; vector<int> path; path.push_back(root->val); traversal(root, path, result, targetSum - root->val); return result; } };
代码(JavaScript)
/** * @param {TreeNode} root * @param {number} targetSum * @return {number[][]} */ function traversal(node, path, result, count) { if (!node.left && !node.right) { if (count === 0) result.push([...path]); // 不能写result.push(path), 要深拷贝 return; } if (node.left) { path.push(node.left.val); count -= node.left.val; traversal(node.left, path, result, count); //递归 count += node.left.val; //回溯 path.pop(); //回溯 } if (node.right) { path.push(node.right.val); count -= node.right.val; traversal(node.right, path, result, count); //递归 count += node.right.val; //回溯 path.pop(); //回溯 } return false; } var pathSum = function(root, targetSum) { let result = []; if (root === null) return result; let path = []; path.push(root.val); traversal(root, path, result, targetSum - root.val); return result; };