-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePostorder.java
More file actions
32 lines (28 loc) · 1012 Bytes
/
BinaryTreePostorder.java
File metadata and controls
32 lines (28 loc) · 1012 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.ArrayList;
import java.util.List;
public class BinaryTreePostorder {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
// Calling preorderTraversal method
List<Integer> postorderList = postorderTraversal(root);
// Printing the result
System.out.println("Postorder traversal: " + postorderList);
}
public static List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
postorder(root, result);
return result;
}
private static void postorder(TreeNode node, List<Integer> result) {
if (node == null) {
return;
}
postorder(node.left, result);
result.add(node.val); // Add the value to the result list
postorder(node.right, result);
}
}