欢迎fork and star:Nowcoder-Repository-github
113. Path Sum II
题目
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
解析
采用dfs和bfs的方法,很经典的方法,类似的题目很多都可以采用此方法,熟练掌握!
class Solution_113 { public:
void dfs(TreeNode* root,int cur_sum,int sum,vector<int> &vec ,vector<vector<int>> &vecs) { if (!root) { return; } if (root->left==NULL&&root->right==NULL&&cur_sum==sum) { vecs.push_back(vec); return; } if (root->left) { vec.push_back(root->left->val); dfs(root->left, cur_sum + root->left->val, sum, vec, vecs); vec.pop_back(); } if (root->right) { vec.push_back(root->right->val); dfs(root->right, cur_sum + root->right->val, sum, vec, vecs); vec.pop_back(); } return; } vector<vector<int> > pathSum1(TreeNode *root, int sum) { vector<vector<int>> vecs; vector<int> vec; if (!root) { return vecs; } vec.push_back(root->val); dfs(root,root->val,sum,vec,vecs); //输入当前节点及其当前节点的和 return vecs; } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int>> vecs; if (!root) { return vecs; } queue<TreeNode*> que; que.push(root); queue<vector<int>> path; path.push({ root->val }); while (!que.empty()) { TreeNode* temp; int size = que.size(); for (int i = 0; i < size;i++) { temp = que.front(); que.pop(); vector<int> vec= path.front(); path.pop(); if (temp->left==NULL&&temp->right==NULL&& accumulate(vec.begin(),vec.end(),0)==sum) //0 累加的初始值 { vecs.push_back(vec); } if (temp->left) { que.push(temp->left); vector<int> var = vec; var.push_back(temp->left->val); path.push(var); //vec.pop_back(); } if (temp->right) { que.push(temp->right); vector<int> var = vec; var.push_back(temp->right->val); path.push(var); //vec.pop_back(); } } } return vecs; }
};