From 6dd9622a70150e8c7359f51b74374e9c003e9631 Mon Sep 17 00:00:00 2001 From: Hriday-A Date: Mon, 4 May 2026 02:22:20 -0500 Subject: [PATCH] completed Trees-2 Assignemt --- postorder_inorder_contruct_tree.java | 42 ++++++++++++++++++++++++++++ sum_root_to_leaf.java | 37 ++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 postorder_inorder_contruct_tree.java create mode 100644 sum_root_to_leaf.java diff --git a/postorder_inorder_contruct_tree.java b/postorder_inorder_contruct_tree.java new file mode 100644 index 00000000..1b91ad47 --- /dev/null +++ b/postorder_inorder_contruct_tree.java @@ -0,0 +1,42 @@ +// time complexity: O(n) +// space complexity : O(n) +/** + * Definition for a binary tree node. + * 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; + * } + * } + */ +class Solution { + int idx; + public TreeNode buildTree(int[] inorder, int[] postorder) { + HashMap map = new HashMap<>(); + for(int i=0; i map){ + //base + if(st>end) return null; //--> this works because we need null in cases the values are missing + //logic + int rootVal = postorder[idx]; + idx--; + TreeNode root= new TreeNode(rootVal); + int rootIdx= map.get(rootVal); + //right + root.right = helper(postorder,rootIdx+1,end,map); + //left + root.left = helper(postorder,st, rootIdx-1,map); + return root; + } +} \ No newline at end of file diff --git a/sum_root_to_leaf.java b/sum_root_to_leaf.java new file mode 100644 index 00000000..db0d3375 --- /dev/null +++ b/sum_root_to_leaf.java @@ -0,0 +1,37 @@ +//time comp : O(n) +//space comp: O(1) +//using recusrion to parse to each node of tree and add the values in the result which is a global variable +/** + * Definition for a binary tree node. + * 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; + * } + * } + */ +class Solution { + int res; + public int sumNumbers(TreeNode root) { + helper(root,0); + return res; + } + private void helper(TreeNode root, int curr){ + //base + if(root==null) return; + // logic + curr = curr*10+ root.val; + if(root.left==null && root.right==null){ + res+=curr; + } + helper(root.left,curr); + helper(root.right,curr); + + } +} \ No newline at end of file