Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit10217f7

Browse files
Merge pull requestyoungyangyang04#437 from nanaliulei/master
更新二叉树的迭代遍历,增加java代码
2 parents806e72f +007813f commit10217f7

File tree

1 file changed

+74
-1
lines changed

1 file changed

+74
-1
lines changed

‎problems/二叉树的迭代遍历.md

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,82 @@ public:
155155
156156
## 其他语言版本
157157
158-
159158
Java:
160159
160+
```java
161+
// 前序遍历顺序:中-左-右,入栈顺序:中-右-左
162+
class Solution {
163+
public List<Integer> preorderTraversal(TreeNode root) {
164+
List<Integer> result = new ArrayList<>();
165+
if (root == null){
166+
return result;
167+
}
168+
Stack<TreeNode> stack = new Stack<>();
169+
stack.push(root);
170+
while (!stack.isEmpty()){
171+
TreeNode node = stack.pop();
172+
result.add(node.val);
173+
if (node.right != null){
174+
stack.push(node.right);
175+
}
176+
if (node.left != null){
177+
stack.push(node.left);
178+
}
179+
}
180+
return result;
181+
}
182+
}
183+
184+
// 中序遍历顺序: 左-中-右 入栈顺序: 左-右
185+
class Solution {
186+
public List<Integer> inorderTraversal(TreeNode root) {
187+
List<Integer> result = new ArrayList<>();
188+
if (root == null){
189+
return result;
190+
}
191+
Stack<TreeNode> stack = new Stack<>();
192+
TreeNode cur = root;
193+
while (cur != null || !stack.isEmpty()){
194+
if (cur != null){
195+
stack.push(cur);
196+
cur = cur.left;
197+
}else{
198+
cur = stack.pop();
199+
result.add(cur.val);
200+
cur = cur.right;
201+
}
202+
}
203+
return result;
204+
}
205+
}
206+
207+
// 后序遍历顺序 左-右-中 入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果
208+
class Solution {
209+
public List<Integer> postorderTraversal(TreeNode root) {
210+
List<Integer> result = new ArrayList<>();
211+
if (root == null){
212+
return result;
213+
}
214+
Stack<TreeNode> stack = new Stack<>();
215+
stack.push(root);
216+
while (!stack.isEmpty()){
217+
TreeNode node = stack.pop();
218+
result.add(node.val);
219+
if (node.left != null){
220+
stack.push(node.left);
221+
}
222+
if (node.right != null){
223+
stack.push(node.right);
224+
}
225+
}
226+
Collections.reverse(result);
227+
return result;
228+
}
229+
}
230+
```
231+
232+
233+
161234

162235
Python:
163236
```python3

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp