Skip to content

Commit

Permalink
Create iterative_inorder_traversal.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
YoungDevelopers3 authored Oct 6, 2021
1 parent 25a472b commit 2434aab
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions iterative_inorder_traversal.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {

// iterative approach
stack<TreeNode*>s;
vector<int>ans;

TreeNode * cur = root;

if(root==NULL)
return ans;

while(!s.empty() || cur!=NULL)
{
while(cur!=NULL)
{
s.push(cur);
cur = cur->left;
}

cur = s.top();
ans.push_back(cur->val);
s.pop();

cur = cur->right;

}
return ans;




}
};

0 comments on commit 2434aab

Please sign in to comment.