iT邦幫忙

2025 iThome 鐵人賽

0

Binary Tree Inorder Traversal (DFS)

LC 94 題意

  • 給定一棵二元樹,回傳其中序遍歷 (Left → Root → Right)。
  • Example
    Input: [1,null,2,3]
    Output: [1,3,2]

thoughts

  • 遞迴 (DFS):最直覺方式。
  • 迭代 (Stack):手動模擬遞迴堆疊。

Kotlin — 遞迴

class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

class Solution {
    fun inorderTraversal(root: TreeNode?): List<Int> {
        val result = mutableListOf<Int>()
        fun dfs(node: TreeNode?) {
            if (node == null) return
            dfs(node.left)
            result.add(node.`val`)
            dfs(node.right)
        }
        dfs(root)
        return result
    }
}

Kotlin — 迭代

class Solution {
    fun inorderTraversal(root: TreeNode?): List<Int> {
        val stack = ArrayDeque<TreeNode>()
        val result = mutableListOf<Int>()
        var curr = root

        while (curr != null || stack.isNotEmpty()) {
            while (curr != null) {
                stack.addLast(curr)
                curr = curr.left
            }
            curr = stack.removeLast()
            result.add(curr.`val`)
            curr = curr.right
        }
        return result
    }
}

Follow-up

  • 若要改成 Preorder 或 Postorder 怎麼改?
  • 若不使用遞迴與 Stack(O(1) 空間)?(→ Morris Traversal)
  • 若節點含有 parent pointer,如何反向遍歷?

上一篇
#31
系列文
來都來了-涮就涮吧33
  1. 29
    #28
  2. 30
    #29
  3. 31
    #30
  4. 32
    #31
  5. 33
    #32
完整目錄
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言