[Question]
Given a binary tree, return the postorder traversal of its nodes 'values.
For example:
Given Binary Tree{1,#,2,3}
,
1 2 / 3
Return[3,2,1]
.
Note: recursive solution is trivial, cocould You Do It iteratively?
Question]
Non-recursive Traversal
[Idea]
Maintain two stacks. One stack is used to store tags, and the right subtree of the corresponding node is traversed. The other stack is used to simulate post-sequential traversal.
[Code]
/*** Definition for binary tree * struct treenode {* int val; * treenode * left; * treenode * right; * treenode (int x): Val (x ), left (null), right (null) {}*}; */class solution {public: vector <int> postordertraversal (treenode * root) {vector <int> result; treenode * node = root; stack <treenode *> st; stack <bool> st_flag; while (node) {St. push (node); st_flag.push (false); node = node-> left;} while (! St. Empty () {bool status = st_flag.top (); If (! Status) {// access the right subtree st_flag.pop (); st_flag.push (true); node = ST. top (); node = node-> right; while (node) {St. push (node); st_flag.push (false); node = node-> left ;}} else {// access the current node st_flag.pop (); node = ST. top (); ST. pop (); result. push_back (node-> Val) ;}} return result ;}};