Title Description:
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, could do it iteratively?
The sequential traversal of binary tree
Recursive algorithm:
Class Solution {public: vector<int> postordertraversal (treenode* root) { vector<int>res; if (root==null) return res; return Postorder (root,res); } Vector<int> postorder (treenode* root,vector<int>& res) { if (root) { Postorder ( Root->left,res); Postorder (root->right,res); Res.push_back (Root->val); } return res; }};
Iterative algorithm:
Class Solution {public: vector<int> postordertraversal (treenode* root) { vector<int>res; if (root==null) return res; Stack<treenode*> Qu; treenode* Node=root; while (!qu.empty () | | node) { if (node) { Qu.push (node); Res.push_back (node->val); node=node->right; } else { treenode* cur=qu.top (); Qu.pop (); node=cur->left; } } Reverse (Res.begin (), Res.end ()); return res; }};
Summary of the first order, the middle sequence, the order can be recursive, iterative implementation.
Recursion: First Order: Output node->pre function (left)->pre function (right): Inorder function (left), Output node->inorder function (right) post order: Postorder function (left )->postorder function (right), output node
Iteration: The implementation of the stack; First order: The top element of the output stack, the top element of the stack is added to the right node, the top element of the stack, the top element of the output stack. Loop in turn. Middle order: The left node is all added to the stack, the top element of the output stack, and joins the top element right node, the left node is all added to the stack. Loop in turn. Post-entry: Read root node, join the right node of the right node of the root node (join a read once, that is, the output of the element), and join the left node of the stack top element (output this element), join the right node of the node right node (join once read, That is, the output of the element). Finally, flipping the output sequence is the iterative algorithm of the post-order traversal. A little more difficult. This article lists the recursive and iterative algorithms for post-routing traversal. Please refer to http://blog.csdn.net/sinat_24520925/article/details/45603147http://blog.csdn.net/sinat_24520925/for first order and middle order article/details/45621865
Leetcode--binary Tree postorder Traversal