Skip to content

Commit 1f59565

Browse files
author
Joseph Luce
authored
Update 145_binary_tree_postorder_traversal.md
1 parent e2d054d commit 1f59565

File tree

1 file changed

+17
-21
lines changed

1 file changed

+17
-21
lines changed

leetcode/hard/145_binary_tree_postorder_traversal.md

+17-21
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
- N = Number of elements in tree
77
- H = Height of tree
88

9-
Post order is left, right, node.
9+
Post order is (Left -> Right -> Node).
1010

1111
The recusive solution is fairly easy. Most of the heavy lifting is abstracted away by the recursion call.
1212

@@ -31,28 +31,24 @@ class Solution:
3131
- N = Number of elements in tree
3232
- H = Height of tree
3333

34-
The iterative solution for post order is fairly diffucult to come up with on your own.
35-
It requires two stacks.
36-
The first stack is used to traverse the tree but in the opposite direction (node -> right -> left).
37-
During the traversal, the 1st stack will transfer its nodes to the 2nd stack, this will place the nodes in the reverse order or post-order (left -> right -> node) when they are popped off the stack later.
38-
I recommend drawing this out, as its important to understand the relationships and responsibilities.
34+
Take a look back at how a preorder is done (Node -> Left -> Right).
35+
Compared to postorder (Left -> Right -> Node), what are some similarities?
36+
You may notice that you can perform a postorder with an inverted preorder traversal.
37+
38+
Another way to look at it is, since postorder is (Left -> Right -> Node), we can go (Node -> Right -> Left) and reverse the result at the end to get the postorder.
39+
40+
So we can achieve an iterative postorder traversal via. an inverted preorder traversal.
3941

4042
```
4143
class Solution:
4244
def postorderTraversal(self, root: TreeNode) -> List[int]:
43-
if root is None:
44-
return []
45-
stack1, stack2 = list([root]), list()
46-
result = list()
47-
while len(stack1) > 0:
48-
node = stack1.pop()
49-
stack2.append(node)
50-
if node.left is not None:
51-
stack1.append(node.left)
52-
if node.right is not None:
53-
stack1.append(node.right)
54-
while len(stack2) > 0:
55-
node = stack2.pop()
56-
result.append(node.val) # <-- Business logic goes here
57-
return result
45+
stack = list([root])
46+
inverted_preorder = list()
47+
while stack:
48+
node = stack.pop()
49+
if node:
50+
inverted_preorder.append(node.val)
51+
stack.append(node.left)
52+
stack.append(node.right)
53+
return inverted_preorder[::-1]
5854
```

0 commit comments

Comments
 (0)