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

Commit626f44a

Browse files
authored
Create 0145-binary-tree-postorder-traversal
Adding the Java solutions for the Postorder traversal
1 parent9603026 commit626f44a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution {
2+
// Iterative
3+
public List<Integer> postorderTraversal(TreeNode root) {
4+
Stack<TreeNode> stack = new Stack<>();
5+
stack.add(root);
6+
Stack<Boolean> visit = new Stack<>();
7+
visit.add(false);
8+
9+
List<Integer> res = new ArrayList<>();
10+
11+
while(!stack.isEmpty()){
12+
TreeNode curr=stack.pop();
13+
boolean v = visit.pop();
14+
if(curr != null){
15+
if(v != false){
16+
res.add(curr.val);
17+
}else{
18+
stack.add(curr);
19+
visit.add(true);
20+
stack.add(curr.right);
21+
visit.add(false);
22+
stack.add(curr.left);
23+
visit.add(false);
24+
}
25+
}
26+
}
27+
return res;
28+
}
29+
}
30+
31+
class Solution {
32+
// Recursive
33+
public void postorder(TreeNode root, List<Integer> res){
34+
if(root == null) return;
35+
36+
postorder(root.left, res);
37+
postorder(root.right, res);
38+
res.add(root.val);
39+
}
40+
public List<Integer> postorderTraversal(TreeNode root) {
41+
List<Integer> res = new ArrayList<>();
42+
43+
postorder(root, res);
44+
return res;
45+
}
46+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp