hello-algo/codes/kotlin/chapter_tree/binary_tree_dfs.kt
curtishd 4d9bbe72e1
Improve the consistency between code and comments in Kotlin (#1268)
* style(kotlin): Make code and comments consistent.

* style(kotlin): convert comment location.

* style(c): Add missing comment.

* style(kotlin): Remove redundant semicolon, parenthesis and brace

* style(kotlin): Put constants inside the function.

* style(kotlin): fix unnecessary indentation.

* style(swift): Add missing comment.

* style(kotlin): Add missing comment.

* style(kotlin): Remove redundant comment.

* style(kotlin): Add missing comment.

* Update linked_list.kt

* style(csharp,js,ts): Add missing comment.

* style(kotlin): Remove empty lines.

* Update list.cs

* Update list.js

* Update list.ts

* roll back to commit 1

* style(cs,js,ts): Add missing comment in docfile.

* style(kotlin): Use normal element swapping instead of scope functions.
2024-04-13 20:09:39 +08:00

64 lines
No EOL
1.5 KiB
Kotlin

/**
* File: binary_tree_dfs.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_tree
import utils.TreeNode
import utils.printTree
// 初始化列表,用于存储遍历序列
var list = mutableListOf<Int>()
/* 前序遍历 */
fun preOrder(root: TreeNode?) {
if (root == null) return
// 访问优先级:根节点 -> 左子树 -> 右子树
list.add(root._val)
preOrder(root.left)
preOrder(root.right)
}
/* 中序遍历 */
fun inOrder(root: TreeNode?) {
if (root == null) return
// 访问优先级:左子树 -> 根节点 -> 右子树
inOrder(root.left)
list.add(root._val)
inOrder(root.right)
}
/* 后序遍历 */
fun postOrder(root: TreeNode?) {
if (root == null) return
// 访问优先级:左子树 -> 右子树 -> 根节点
postOrder(root.left)
postOrder(root.right)
list.add(root._val)
}
/* Driver Code */
fun main() {
/* 初始化二叉树 */
// 这里借助了一个从列表直接生成二叉树的函数
val root = TreeNode.listToTree(mutableListOf(1, 2, 3, 4, 5, 6, 7))
println("\n初始化二叉树\n")
printTree(root)
/* 前序遍历 */
list.clear()
preOrder(root)
println("\n前序遍历的节点打印序列 = $list")
/* 中序遍历 */
list.clear()
inOrder(root)
println("\n中序遍历的节点打印序列 = $list")
/* 后序遍历 */
list.clear()
postOrder(root)
println("\n后序遍历的节点打印序列 = $list")
}