forked from apachecn/Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request apachecn#292 from royIdoodle/master
094. Binary Tree Inorder Traversal
- Loading branch information
Showing
1 changed file
with
106 additions
and
0 deletions.
There are no files selected for viewing
106 changes: 106 additions & 0 deletions
106
docs/Algorithm/Leetcode/JavaScript/0094._Binary_Tree_Inorder_Traversal.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
# 094. Binary Tree Inorder Traversal | ||
|
||
**<font color=orange>难度: Medium</font>** | ||
|
||
## 刷题内容 | ||
|
||
> 原题连接 | ||
* [https://leetcode-cn.com/problems/binary-tree-inorder-traversal/](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/) | ||
|
||
> 内容描述 | ||
给定一个二叉树,返回它的*中序* 遍历。 | ||
|
||
**示例:** | ||
|
||
``` | ||
输入: [1,null,2,3] | ||
1 | ||
\ | ||
2 | ||
/ | ||
3 | ||
输出: [1,3,2] | ||
``` | ||
|
||
|
||
## 解题方案 | ||
|
||
> 思路 1 迭代 | ||
> **- 时间复杂度: O(3N)** | ||
> | ||
> **- 空间复杂度: O(N)** | ||
> 执行用时 :**64 ms**, 在所有 JavaScript 提交中击败了**97.85%**的用户 | ||
> | ||
> 内存消耗 :**33.7 MB**, 在所有 JavaScript 提交中击败了**34.70%**的用户 | ||
```javascript | ||
/** | ||
* Definition for a binary tree node. | ||
* function TreeNode(val) { | ||
* this.val = val; | ||
* this.left = this.right = null; | ||
* } | ||
*/ | ||
/** | ||
* @param {TreeNode} root | ||
* @return {number[]} | ||
*/ | ||
const inorderTraversal = node => { | ||
const valueList = [] | ||
forEachTree(node) | ||
return valueList | ||
function forEachTree (node) { | ||
if (!node) { | ||
return | ||
} | ||
forEachTree(node.left) | ||
valueList.push(node.val) | ||
forEachTree(node.right) | ||
} | ||
} | ||
``` | ||
|
||
|
||
|
||
> 思路 2 迭代 | ||
> | ||
> - 时间复杂度: O(N²) | ||
> - 空间复杂度: O(N²) | ||
>执行用时 :**76 ms**, 在所有 JavaScript 提交中击败了**69.05%**的用户 | ||
> | ||
>内存消耗 :**33.7 MB**, 在所有 JavaScript 提交中击败了**36.57%**的用户 | ||
```javascript | ||
/** | ||
* Definition for a binary tree node. | ||
* function TreeNode(val) { | ||
* this.val = val; | ||
* this.left = this.right = null; | ||
* } | ||
*/ | ||
/** | ||
* @param {TreeNode} root | ||
* @return {number[]} | ||
*/ | ||
const inorderTraversal = (node) => { | ||
const valList = [] | ||
const stack = [] | ||
while (node || stack.length) { | ||
if (node) { | ||
stack.push(node) | ||
node = node.left | ||
} else { | ||
node = stack.pop() | ||
valList.push(node.val) | ||
node = node.right | ||
} | ||
} | ||
return valList | ||
}; | ||
``` | ||
|