Skip to content

Commit

Permalink
Merge pull request apachecn#292 from royIdoodle/master
Browse files Browse the repository at this point in the history
094. Binary Tree Inorder Traversal
  • Loading branch information
jiangzhonglian authored Aug 29, 2019
2 parents 5a54639 + ca3a44d commit 4088054
Showing 1 changed file with 106 additions and 0 deletions.
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
};
```

0 comments on commit 4088054

Please sign in to comment.