Path Sum II
Total Accepted: 41402 Total Submissions: 155034My Submissions
Question Solution
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] ]
Hide Tags
Have you met this question in a real interview?
Yes
No
这道题采用深度优先搜索的算法来做,由于想记录下从根节点到每个节点的各个节点,所以在用堆栈的时候没有多加了一个向量来存储路径
#include<iostream> #include<stack> #include<utility> #include<vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > result; if(root==NULL) return result; stack<pair<TreeNode*,vector<int> > > sta_temp; vector<int> temp; temp.push_back(root->val); sta_temp.push(make_pair(root,temp)); vector<int> Vtemp_top; TreeNode* Ttemp_top; while(!sta_temp.empty()) { Vtemp_top=sta_temp.top().second; Ttemp_top=sta_temp.top().first; sta_temp.pop(); if(Ttemp_top->left==NULL&&Ttemp_top->right==NULL) { int sum_temp=0; for(int i=0;i!=Vtemp_top.size();i++) { sum_temp+=Vtemp_top[i]; } if(sum_temp==sum) { result.push_back(Vtemp_top); } } if(Ttemp_top->left!=NULL) { Vtemp_top.push_back(Ttemp_top->left->val); sta_temp.push(make_pair(Ttemp_top->left,Vtemp_top)); Vtemp_top.pop_back(); } if(Ttemp_top->right!=NULL) { Vtemp_top.push_back(Ttemp_top->right->val); sta_temp.push(make_pair(Ttemp_top->right,Vtemp_top)); //temp.pop_back(); } } return result; } int main() { TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode)); root->val=1; root->right=NULL; root->left=(TreeNode*)malloc(sizeof(TreeNode)); root->left->val=2; root->left->left=NULL; root->left->right=NULL; vector<vector<int> > temp; temp=pathSum(root,1); }
时间: 2025-01-20 02:17:34