forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0145-binary-tree-postorder-traversal.kt
55 lines (45 loc) · 1.49 KB
/
0145-binary-tree-postorder-traversal.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// iterative solution
class Solution {
fun postorderTraversal(root: TreeNode?): List<Int> {
val res = ArrayList<Int>()
val stack = Stack<TreeNode>()
if (root != null) stack.push(root)
while (!stack.isEmpty()) {
val node = stack.pop()
res.add(0, node.`val`)
if (node.left != null) stack.push(node.left)
if (node.right != null) stack.push(node.right)
}
return res
}
}
//iterative solution, doing preorder traversal BUT adding left before right, and at end reversing the result list to get correct order
class Solution {
fun postorderTraversal(root: TreeNode?): List<Int> {
val res = ArrayList<Int>()
val stack = Stack<TreeNode>()
if (root != null) stack.push(root)
while (!stack.isEmpty()) {
val node = stack.pop()
res.add(node.`val`)
if(node.left != null) stack.push(node.left)
if(node.right != null) stack.push(node.right)
}
res.reverse()
return res
}
}
//recursion version
class Solution {
fun postorderTraversal(root: TreeNode?): List<Int> {
val res = ArrayList<Int>()
fun postOrder(node: TreeNode?) {
node?: return
postOrder(node.left)
postOrder(node.right)
res.add(node.`val`)
}
postOrder(root)
return res
}
}