Jayakrishna14

Postorder

Aug 25th, 2024
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 KB | None | 0 0
  1.  
  2. class Solution {
  3. public:
  4.     vector<int> postorderTraversal(TreeNode* root) {
  5.         vector<int> ans;
  6.        
  7.         while(root!=nullptr){
  8.             ans.push_back(root->val);
  9.             if(root->right == nullptr){
  10.                 root = root->left;
  11.             }
  12.             else{
  13.                 TreeNode* next = root->right;
  14.                 while(next->left!=nullptr){
  15.                     next = next->left;
  16.                 }
  17.                 next->left = root->left;
  18.                 TreeNode* temp = root;
  19.                 root = root->right;
  20.                 temp->left=nullptr;
  21.                
  22.             }
  23.         }
  24.  
  25.         reverse(ans.begin(), ans.end());
  26.         return ans;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment