Problem:
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?
Hide TagsTree StackTest instructions: Non-recursive follow-up traversal of binary tree
Thinking:
(1) The method of non-recursive follow-up traversal of binary tree is abstract, with two stacks
(2) The use of double stack switching, the first stack out of the stack, two children (first left and right) into the stack, the nodes out of the stack to save to the second stack. The second stack in turn is the result of subsequent traversal.
Code
Class Solution {public : vector<int> postordertraversal (treenode* root) { Stack<treenode *> input; Stack<treenode *> output; vector<int> ret; if (root==null) return ret; TreeNode *node = root; Input.push (node); while (!input.empty ()) { node=input.top (); Input.pop (); Output.push (node); if (node->left!=null) Input.push (node->left); if (node->right!=null) Input.push (node->right); } while (!output.empty ()) { node=output.top (); Output.pop (); Ret.push_back (Node->val); } return ret; } };
Leetcode | | 145, Binary Tree postorder traversal