145. Binary Tree Post Order Traversal
Last updated
Was this helpful?
Last updated
Was this helpful?
Given a binary tree, return thepostordertraversal of its nodes' values.
For example:
Given binary tree{1,#,2,3}
,
return[3,2,1]
.
Note:Recursive solution is trivial, could you do it iteratively?
Trivial Solution:
Recursion Call
Reverse the output
Thoughts:
Using stack: generalized the : O(n) in time and O(n) in space 1. For postorder traversal, we visit a node when popping it. last_pop represents the node which is popped the last time. For the top node in stack, it has three choices, pushing its left child in stack, or pushing its right child in stack, or being popped. If last_pop != top->left, meaning that its left tree has not been pushed in stack, then we push its left child. If last_pop == top->left, we push its right child. Otherwise, we pop the top node. 2. In contrast, for , we visit a node when pushing it in stack. For , we visit a node when pushing its right child in stack.
Always use a lastNode, the (last node added to the answer), to keep track whether cur-> right is the same as that (if it is then, we need to visit the CurNode, if it is not, then we need to first visit cur->right)
Morris Traversal (Adopted from 's ) : O(n) in time and O(1) in space
Code 1:
Code 2: Morris Traversal (hard):
Visit left subtree find the right the rightmost tree, add a cycle to the current node - left subtree - right most point
Iteratively creating cycles to the left (left) , until we detect a cycle, process the answer for the left subtree using three pointers, then move to the right subtree root, repeat 2 (right).
right subtree root and current node are included when cycle between right subtree - root, current node - and parent is detected ( reason why to add a dummy node as the root)
Code 1 by 's :
Code 2 : Better Morris Traversal from