Jayakrishna14

Untitled

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