# C++ iterative solution with stack of pairs

• ``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ret_vec;
if(root == NULL){
return ret_vec;
}

TreeNode* pt = root;
stack<pair<TreeNode*, string>> tree_stack;
tree_stack.push(pair<TreeNode*, string>(pt, to_string(pt->val)));

while(!tree_stack.empty()){

pt = (tree_stack.top().first);
string temp = tree_stack.top().second;
tree_stack.pop();
if(pt->right != NULL){
tree_stack.push(pair<TreeNode*, string>(pt->right, temp + "->" + to_string(pt->right->val)));
}
if(pt->left != NULL){
tree_stack.push(pair<TreeNode*, string>(pt->left, temp + "->" + to_string(pt->left->val)));
}
if(pt->left == NULL && pt->right == NULL){
ret_vec.push_back(temp);
}
}

return ret_vec;
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.