题目
给你二叉树的根节点 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 输出:[]
解题
方法一:BFS
class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int target) { if(!root) return {}; vector<vector<int>> res; queue<TreeNode*> queueNode; queue<int> queueVal; queue<vector<int>> queueVec; queueNode.push(root); queueVal.push(root->val); queueVec.push(vector<int>{root->val}); while(!queueNode.empty()){ TreeNode* cur=queueNode.front(); queueNode.pop(); int val=queueVal.front(); queueVal.pop(); vector<int> vec=queueVec.front(); queueVec.pop(); if(!(cur->left||cur->right)&&val==target){ res.push_back(vec); } if(cur->left){ queueNode.push(cur->left); queueVal.push(val+cur->left->val); vec.push_back(cur->left->val); queueVec.push(vec); vec.pop_back(); } if(cur->right){ queueNode.push(cur->right); queueVal.push(val+cur->right->val); vec.push_back(cur->right->val); queueVec.push(vec); vec.pop_back(); } } return res; } };
方法二:回溯
class Solution { public: vector<vector<int>> res; vector<int> path; void dfs(TreeNode* root,int target){ if(!root) return; path.push_back(root->val); target-=root->val; if(target==0&&!(root->left||root->right)) res.push_back(path); dfs(root->left,target); dfs(root->right,target); path.pop_back();//回溯 } vector<vector<int>> pathSum(TreeNode* root, int target) { dfs(root,target); return res; } };