Path sum II |leetcode c++

来源:互联网 发布:老炮儿 网络剧 编辑:程序博客网 时间:2024/06/06 12:58

I use iterate method to solve this problem. 

1.I use the hash table unordered_map to record whether the node is visited.

2.i made a mistake so that the program entered an endless loop, Please see the detail information in the comment of the code.

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:     vector<vector<int> > pathSum(TreeNode *root, int sum) {     vector<vector<int>> ans;     int sum_stack = 0;     if(root == NULL)     return ans;       vector<int> cur(0);     stack<TreeNode *> s;     s.push(root);     cur.push_back(root->val);     sum_stack = root->val;     unordered_map<TreeNode *,bool> visited;     visited[root] = true;     while(!s.empty())     {        TreeNode * temp = s.top();     if(temp->left!=NULL && !visited[temp->left])     {     s.push(temp->left);     cur.push_back(temp->left->val);     visited[temp->left] = true;     sum_stack +=temp->left->val;     continue;     }     if(temp->right != NULL && !visited[temp->right])     {     s.push(temp->right);     cur.push_back(temp->right->val);     visited[temp->right] = true;     sum_stack +=temp->right->val;     continue;     }     if(sum_stack == sum && temp->left == NULL &&temp->right == NULL)//at first I write a else after this if sentence, then      //it entered an endless loop. because it excurte ans.push_back(cur) over and over;     ans.push_back(cur);        sum_stack -= s.top()->val;     s.pop();     cur.pop_back();     }     return ans;    }};

 

0 0
原创粉丝点击