## 94. Binary Tree Inorder Traversal > Given the root of a binary tree, return the inorder traversal of its nodes' values. ``` Example 1: Input: root = [1,null,2,3] Output: [1,3,2] ``` Explanation:  ### 題目描述: > 給定一個節點樹,要求以中序遍歷 (Inorder Traversal) 的方式,輸出節點值的序列。 ### 中序遍歷順序: - 左子樹 → 根節點 → 右子樹 ### 解題思路: 中序遍歷的主要邏輯是: - 遍歷左子樹 - 訪問當前節點 - 遍歷右子樹 - 這可以通過 遞迴 或 迭代 的方式實現。 > 以前碰到 Tree 題型,一直搞不懂原理,直到我開始沈住氣慢慢一句句看才發現,`root` 資料其實就是 `TreeNode` 的實例,我們只需要利用它裡頭的 `property` 去處理業務邏輯就好,有種恍然大悟的感覺。 ### 個人偏好遞迴方式處理 #### Code ```javascript= /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number[]} */ function inorderTraversal(root) { const result = []; function traverse(node) { if (!node) return; // 如果節點為 null,直接返回 traverse(node.left); // 遍歷左子樹 result.push(node.val); // 訪問節點 traverse(node.right); // 遍歷右子樹 } traverse(root); return result; } ``` ### 時間與空間複雜度: - 時間複雜度:O(n),每個節點只會被訪問一次。 - 空間複雜度:O(h),h 是遞迴調用的最大深度(樹的高度)。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up