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
classSolution {
funpreorderTraversal(root:TreeNode?): List<Int> {
// return recursiveDfs(root)return iterativeDfs(root)
}
/* DFS : Recursive. get all left-first traversed list and right traversed list*/funrecursiveDfs(root:TreeNode?): List<Int> {
root ?:returnlistOf()
returnlistOf(root.`val`) + preorderTraversal(root.left) + preorderTraversal(root.right)
}
/* DFS : Iterative. contrary to BFS with 'Queue', DFS have to use 'Stack'.*/funiterativeDfs(root:TreeNode?): List<Int> {
root ?:returnlistOf()
val result = mutableListOf<Int>()
val stack =Stack<TreeNode>()
stack.add(root)
// traversewhile (stack.isNotEmpty()) {
val node = stack.pop()
result.add(node.`val`)
// to traverse first on left, add right first.
node.right?.let { stack.push(it) }
node.left?.let { stack.push(it) }
}
return result
}
}
94. Binary Tree Inorder Traversal
langkotlin
tagsStackDFSTreeBinary Tree
classSolution {
funinorderTraversal(root:TreeNode?): List<Int> {
// return recursiveDfs(root)return iterativeDfs(root)
}
funrecursiveDfs(root:TreeNode?): List<Int> {
root ?:returnlistOf()
return recursiveDfs(root.left) +listOf(root.`val`) + recursiveDfs(root.right)
}
funiterativeDfs(root:TreeNode?): List<Int> {
val result = mutableListOf<Int>()
var cursor = root
val stack =Stack<TreeNode>()
// traverse until non-empty-stack & cursor existswhile (stack.isNotEmpty() || cursor !=null) {
/* for iterative inorder traversal # if possible to go down to left, enroll each node to stack. # from left bottom, up to top cursor with traverse each's right nodes.*/if (cursor !=null) {
stack.push(cursor)
cursor = cursor.left
} else {
cursor = stack.pop()
cursor?.let { result.add(it.`val`) }
cursor = cursor.right
}
}
return result
}
}
145. Binary Tree Postorder Traversal
langkotlin
tagsStackDFSTreeBinary Tree
classSolution {
funpostorderTraversal(root:TreeNode?): List<Int> {
// return recursiveDfs(root)return iterativeDfs(root)
}
funrecursiveDfs(root:TreeNode?): List<Int> {
root ?:returnlistOf()
return recursiveDfs(root.left) + recursiveDfs(root.right) +listOf(root.`val`)
}
funiterativeDfs(root:TreeNode?): List<Int> {
val result = mutableListOf<Int>()
var cursor:TreeNode?= root
var prev:TreeNode?=nullval stack =Stack<TreeNode>()
while (stack.isNotEmpty() || cursor !=null) {
/* for iterative inorder traversal # if possible to go down to left, enroll each node to stack. # traverse 1) from last saved node, move down to last right node. 2) save already read cursor to prev and traverse reverse order.*/if (cursor !=null) {
stack.push(cursor)
cursor = cursor.left
} else {
cursor = stack.peek()
if (cursor.right ==null|| cursor.right == prev) {
result.add(cursor.`val`)
stack.pop()
prev = cursor
cursor =null
} else cursor = cursor.right
}
}
return result
}
}