From 8ab17a79b26831bf686fa5fb180404892a984cf7 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 25 Aug 2024 14:11:31 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB145.=20Binary=20Tree=20Post?= =?UTF-8?q?order=20Traversal=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/TreeNode.java | 17 +++++++++++++++++ java/binary-tree-postorder-traversal.java | 20 ++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 java/TreeNode.java create mode 100644 java/binary-tree-postorder-traversal.java diff --git a/java/TreeNode.java b/java/TreeNode.java new file mode 100644 index 0000000..8fdc9b6 --- /dev/null +++ b/java/TreeNode.java @@ -0,0 +1,17 @@ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode() {} + + TreeNode(int val) { + this.val = val; + } + + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } +} diff --git a/java/binary-tree-postorder-traversal.java b/java/binary-tree-postorder-traversal.java new file mode 100644 index 0000000..5135117 --- /dev/null +++ b/java/binary-tree-postorder-traversal.java @@ -0,0 +1,20 @@ +import java.util.ArrayList; +import java.util.List; + +class Solution { + private ArrayList postorderTraversal(TreeNode node, ArrayList l) { + if (node == null) { + return l; + } + + postorderTraversal(node.left, l); + postorderTraversal(node.right, l); + + l.add(node.val); + return l; + } + + public List postorderTraversal(TreeNode root) { + return postorderTraversal(root, new ArrayList()); + } +}