You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: leetcode/hard/145_binary_tree_postorder_traversal.md
+17-21
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,7 @@
6
6
- N = Number of elements in tree
7
7
- H = Height of tree
8
8
9
-
Post order is left, right, node.
9
+
Post order is (Left -> Right -> Node).
10
10
11
11
The recusive solution is fairly easy. Most of the heavy lifting is abstracted away by the recursion call.
12
12
@@ -31,28 +31,24 @@ class Solution:
31
31
- N = Number of elements in tree
32
32
- H = Height of tree
33
33
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.
0 commit comments