递归: vector<int> vec; void process(TreeNode *root) { if(root == NULL)return ; process(root->left); process(root->right); vec.push_back(root->val); }
非递归:运用前序遍历转换 vector<int> postorderTraversal1(TreeNode *root) { stack<TreeNode*> s; vector<int> v; if(root == NULL)return v; s.push(root); while(!s.empty()){ TreeNode *t = s.top(); v.push_back(t->val); s.pop(); if(t->left)s.push(t->left); if(t->right)s.push(t->right); } reverse(v.begin(),v.end()); //process(root); return v; }
非递归 vector<int> postorderTraversal(TreeNode *root) { stack<TreeNode*> s; vector<int> v; if(root == NULL)return v; s.push(root); while(!s.empty()){ TreeNode *t = s.top(); while(t->left){s.push(t->left);t =t->left;} t = s.top(); if(t->right == NULL) { v.push_back(t->val); s.pop(); if(s.empty())break; TreeNode* r = s.top(); if( r->left == t) r->left = NULL; if(r->right == t) r->right = NULL; }else{ s.push(t->right); } } return v; }