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?
Non-Recursive Method for post-sequential traversal of Binary Trees.
Idea: Use the stack to assist in implementation. First, add the root node to the stack, and then perform cyclic operations with the condition of whether the stack is empty, taking the top element of the stack:
When the top element of the stack is a leaf node (the left and right child nodes of the top element of the stack are null) or the left and right children are traversed out of date (previous is equal to the left child node or the right child node ), then, the stack is output and recorded in the VI array. At the same time, the node is assigned to the previous pointer. The Node traversed this time serves as the previous node of the next judgment.
If none of the above conditions is met, it means that the child node on the top node of the stack has not been traversed, then the left and right child nodes are added to the stack, to ensure that the left child node is in front of the right child node when the stack is out, the right child should first be put into the stack.
AC 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) // non-recursive post-order traversal of {vector <int> VI; If (root = NULL) return VI; treenode * Previous = NULL; stack <treenode *> st; ST. push (Root); While (! St. empty () {root = ST. top (); If (root-> left = NULL & root-> right = NULL) | (previous! = NULL & previous = root-> left) | (previous! = NULL & previous = root-> right) {vi. push_back (root-> Val); ST. pop (); previous = root;} else {If (root-> right! = NULL) ST. Push (root-> right); If (root-> left! = NULL) ST. Push (root-> left) ;}} return VI ;}};