LeetCode之Binary Tree Inorder Traversal(Kotlin)

224 阅读1分钟

问题: image.png


方法: 中序遍历,看码吧。

package com.eric.leetcode

class BinaryTreeInorderTraversal {
    private val result = mutableListOf<Int>()

    fun inorderTraversal(root: TreeNode?): List<Int> {
        result.clear()
        dfs(root)
        return result
    }

    private fun dfs(root: TreeNode?) {
        if (root == null) {
            return
        }
        dfs(root.left)
        result.add(root.`val`)
        dfs(root.right)
    }
}

有问题随时沟通

具体代码实现可以参考Github