Question
Given a binary tree, return the postorder traversal of its nodes’ values.
Example:
|
|
Follow up: Recursive solution is trivial, could you do it iteratively?
Left, Right, root
Answer
Recursive
|
|
Time complexity: O(n), 1ms
Iterative, Using addFirst()
|
|
Time complexity: O(n), 2ms
push node.left first, then node.right, in this way, will addFirst(node.right), then addFirst(add.left) -> left, right, root
Only LinkedList has method addFirst(Element e)
Iterative, Using LastVisit node
|
|
后序遍历在决定是否可以输出当前节点的值的时候,需要考虑其左右子树是否都已经遍历完成。
所以需要设置一个lastVisit游标。
若lastVisit等于当前考查节点的右子树,表示该节点的左右子树都已经遍历完成,则可以输出当前节点。
并把lastVisit节点设置成当前节点,将当前游标节点node设置为空,下一轮就可以访问栈顶元素。