Advertisement
spider68

Binary Tree Postorder Traversal using stack

Jan 14th, 2021
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.52 KB | None | 0 0
  1.  
  2. class Solution {
  3. public:
  4.     vector<int> postorderTraversal(TreeNode* root) {
  5.         if(!root)return {};
  6.         stack<TreeNode*>s1,s2;
  7.         vector<int>v;
  8.         s2.push(root);
  9.         while(!s2.empty()){
  10.             TreeNode*ll=s2.top();
  11.             s2.pop();
  12.             s1.push(ll);
  13.             if(ll->left)s2.push(ll->left);
  14.             if(ll->right)s2.push(ll->right);
  15.         }
  16.         while(!s1.empty()){
  17.             v.push_back(s1.top()->val);
  18.             s1.pop();
  19.         }
  20.         return v;
  21.     }
  22. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement