Skip to content

Commit eb95bf7

Browse files
committed
📝 add lc 94
1 parent 3567a79 commit eb95bf7

2 files changed

Lines changed: 95 additions & 1 deletion

File tree

Java/alg/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,8 @@
133133
- [91.解码方法](lc/91.解码方法.md)
134134
- [92.反转链表2](92.反转链表2.md)
135135
- [93.复原IP地址](93.复原IP地址.md)
136+
- [94.二叉树的中序遍历](94.二叉树的中序遍历.md)
136137

137138
## 笔试
138139

139-
<!-- - [1.分苹果](we/1.分苹果.md) -->
140+
<!-- - [1.分苹果](we/1.分苹果.md) -->
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# 94.二叉树的中序遍历
2+
3+
[url](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/)
4+
5+
## 题目
6+
7+
给定一个二叉树的根节点 `root` ,返回它的 **中序** 遍历。
8+
9+
![](https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg)
10+
11+
12+
```
13+
输入:root = [1,null,2,3]
14+
输出:[1,3,2]
15+
```
16+
17+
## 方法
18+
19+
20+
## code
21+
22+
### js
23+
24+
```js
25+
var inorderTraversal = function(root) {
26+
let ret = [];
27+
if (root === null)
28+
return ret;
29+
let stack = [];
30+
let cur = root;
31+
while (cur !== null || stack.length !== 0) {
32+
while (cur !== null) {
33+
stack.push(cur);
34+
cur = cur.left;
35+
}
36+
let t = stack.pop();
37+
ret.push(t.val)
38+
cur = t.right;
39+
}
40+
return ret;
41+
};
42+
```
43+
44+
### go
45+
46+
```go
47+
func inorderTraversal(root *TreeNode) []int {
48+
var ret []int
49+
if root == nil {
50+
return ret
51+
}
52+
var stack []*TreeNode
53+
cur := root
54+
for cur != nil || len(stack) != 0 {
55+
for cur != nil {
56+
stack = append(stack, cur)
57+
cur = cur.Left
58+
}
59+
t := stack[len(stack)-1]
60+
stack = stack[:len(stack)-1]
61+
ret = append(ret, t.Val)
62+
cur = t.Right
63+
}
64+
return ret
65+
}
66+
```
67+
68+
### java
69+
70+
```java
71+
class Solution {
72+
public List<Integer> inorderTraversal(TreeNode root) {
73+
List<Integer> ret = new ArrayList<>();
74+
if (root == null)
75+
return ret;
76+
Stack<TreeNode> stack = new Stack<>();
77+
78+
TreeNode cur = root;
79+
80+
while (cur != null || !stack.isEmpty()) {
81+
while (cur != null) {
82+
stack.push(cur);
83+
cur = cur.left;
84+
}
85+
TreeNode t = stack.pop();
86+
ret.add(t.val);
87+
cur = t.right;
88+
}
89+
return ret;
90+
}
91+
}
92+
```
93+

0 commit comments

Comments
 (0)