Skip to content

Commit 2c59c4a

Browse files
committed
solve 94.二叉树的中序遍历
1 parent 2c3d9aa commit 2c59c4a

File tree

2 files changed

+121
-0
lines changed

2 files changed

+121
-0
lines changed

zh/94.二叉树的中序遍历.1.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
* @lc app=leetcode.cn id=94 lang=java
3+
*
4+
* [94] 二叉树的中序遍历
5+
*
6+
* https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/
7+
*
8+
* algorithms
9+
* Medium (71.43%)
10+
* Likes: 498
11+
* Dislikes: 0
12+
* Total Accepted: 157.6K
13+
* Total Submissions: 220.6K
14+
* Testcase Example: '[1,null,2,3]'
15+
*
16+
* 给定一个二叉树,返回它的中序 遍历。
17+
*
18+
* 示例:
19+
*
20+
* 输入: [1,null,2,3]
21+
* ⁠ 1
22+
* ⁠ \
23+
* ⁠ 2
24+
* ⁠ /
25+
* ⁠ 3
26+
*
27+
* 输出: [1,3,2]
28+
*
29+
* 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
30+
*
31+
*/
32+
33+
// @lc code=start
34+
/**
35+
* Definition for a binary tree node.
36+
* public class TreeNode {
37+
* int val;
38+
* TreeNode left;
39+
* TreeNode right;
40+
* TreeNode(int x) { val = x; }
41+
* }
42+
*/
43+
class Solution {
44+
public List<Integer> inorderTraversal(TreeNode root) {
45+
List<Integer> result = new ArrayList<>();
46+
if (root == null) {
47+
return result;
48+
}
49+
50+
result.addAll(inorderTraversal(root.left));
51+
result.add(root.val);
52+
result.addAll(inorderTraversal(root.right));
53+
54+
return result;
55+
}
56+
}
57+
// @lc code=end
58+

zh/94.二叉树的中序遍历.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* @lc app=leetcode.cn id=94 lang=java
3+
*
4+
* [94] 二叉树的中序遍历
5+
*
6+
* https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/
7+
*
8+
* algorithms
9+
* Medium (71.43%)
10+
* Likes: 498
11+
* Dislikes: 0
12+
* Total Accepted: 157.6K
13+
* Total Submissions: 220.6K
14+
* Testcase Example: '[1,null,2,3]'
15+
*
16+
* 给定一个二叉树,返回它的中序 遍历。
17+
*
18+
* 示例:
19+
*
20+
* 输入: [1,null,2,3]
21+
* ⁠ 1
22+
* ⁠ \
23+
* ⁠ 2
24+
* ⁠ /
25+
* ⁠ 3
26+
*
27+
* 输出: [1,3,2]
28+
*
29+
* 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
30+
*
31+
*/
32+
33+
// @lc code=start
34+
/**
35+
* Definition for a binary tree node.
36+
* public class TreeNode {
37+
* int val;
38+
* TreeNode left;
39+
* TreeNode right;
40+
* TreeNode(int x) { val = x; }
41+
* }
42+
*/
43+
class Solution {
44+
public List<Integer> inorderTraversal(TreeNode root) {
45+
List<Integer> result = new ArrayList<>();
46+
Stack<TreeNode> stack = new Stack<>();
47+
TreeNode p = root;
48+
49+
while (!stack.empty() || p != null) {
50+
while (p != null) {
51+
stack.push(p);
52+
p = p.left;
53+
}
54+
p = stack.pop();
55+
result.add(p.val);
56+
p = p.right;
57+
}
58+
59+
return result;
60+
}
61+
}
62+
// @lc code=end
63+

0 commit comments

Comments
 (0)