Skip to content

Commit 0b6eec6

Browse files
committed
Update solution 094
1 parent 93938e8 commit 0b6eec6

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

solution/094.Binary Tree Inorder Traversal/README.md

+39-1
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@
1818
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
1919

2020
### 解法
21-
递归算法,先递归左子树,再访问根结点,最后递归右子树。
2221

2322
- 递归算法
2423

24+
先递归左子树,再访问根结点,最后递归右子树。
25+
2526
```java
2627

2728
/**
@@ -49,5 +50,42 @@ class Solution {
4950
inorderTraversal(root.right, list);
5051
}
5152

53+
}
54+
```
55+
56+
- 非递归算法
57+
58+
一直向左找到结点的最左结点,中间每到一个结点,将结点压入栈中。到了最左结点时,输出该结点值,然后对该结点右孩子执行上述循环。
59+
60+
```java
61+
/**
62+
* Definition for a binary tree node.
63+
* public class TreeNode {
64+
* int val;
65+
* TreeNode left;
66+
* TreeNode right;
67+
* TreeNode(int x) { val = x; }
68+
* }
69+
*/
70+
class Solution {
71+
public List<Integer> inorderTraversal(TreeNode root) {
72+
List<Integer> list = new ArrayList<>();
73+
Stack<TreeNode> stack = new Stack<>();
74+
75+
while (root != null || !stack.isEmpty()) {
76+
while (root != null) {
77+
stack.push(root);
78+
root = root.left;
79+
}
80+
if (!stack.isEmpty()) {
81+
root = stack.pop();
82+
list.add(root.val);
83+
root = root.right;
84+
}
85+
}
86+
return list;
87+
88+
}
89+
5290
}
5391
```

solution/094.Binary Tree Inorder Traversal/Solution.java

+27
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// 递归版本
2+
/*
13
class Solution {
24
public List<Integer> inorderTraversal(TreeNode root) {
35
List<Integer> list = new ArrayList<>();
@@ -14,4 +16,29 @@ private void inorderTraversal(TreeNode root, List<Integer> list) {
1416
inorderTraversal(root.right, list);
1517
}
1618
19+
}
20+
21+
*/
22+
23+
// 非递归版本
24+
class Solution {
25+
public List<Integer> inorderTraversal(TreeNode root) {
26+
List<Integer> list = new ArrayList<>();
27+
Stack<TreeNode> stack = new Stack<>();
28+
29+
while (root != null || !stack.isEmpty()) {
30+
while (root != null) {
31+
stack.push(root);
32+
root = root.left;
33+
}
34+
if (!stack.isEmpty()) {
35+
root = stack.pop();
36+
list.add(root.val);
37+
root = root.right;
38+
}
39+
}
40+
return list;
41+
42+
}
43+
1744
}

0 commit comments

Comments
 (0)