First, we briefly introduce the following sequence traversal, the middle sequence traversal and the post-order traversal,
The first order traversal is ABC, the middle order traversal is BAC, the subsequent traversal is BCA, and the root node determines what traversal.
The recursive solution of the problem:
Class Solution {public:typedef TreeNode * streenode;vector<int> buf; Vector<int> postordertraversal (TreeNode *root) { if (root! = NULL) rpostorder (root); return buf; } void Rpostorder (TreeNode *root) { if (Root->left = = NULL && Root->right = = null) { Buf.push_back (root->val); return;} if (root->left! = NULL) { rpostorder (root->left); } if (root->right! = NULL) { rpostorder (root->right);} Buf.push_back (Root->val);}};
The non-recursive solution of the problem:
Class Solution {public:typedef TreeNode * streenode;vector<int> result; Vector<int> postordertraversal (TreeNode *root) {stack<pair<streenode,bool>> buf; if (root = NULL) return result; while (1) {if (Root->left = = NULL && Root->right = = null) {Result.push_back (root-> ; val); Root = GetData (BUF); if (root = NULL) break;} else if (root->left! = NULL) {Buf.push (pair<streenode,bool> (root,true)); if (root->right! = NULL) {Buf.push (pair<streenode,bool> (Root->right,false)); } root = root->left; }else {Buf.push (pair<streenode,bool> (root,true)); root = root->right; }} return result; }streenode GetData (stack<pair<streenode,bool>> &buf) {pair<streenode,bool> temp;if (buf.size ( ) = = 0) return NULL; while (1) {temp = Buf.top (); Buf.pop (); if (Temp.second = = false) break; Result.push_Back ((Temp.first)->val); if (buf.size () = = 0) break; if (Temp.second = = true) return Null;elsereturn Temp.first;}};
Binary Tree postorder Traversal