diff --git a/Problem45.java b/Problem45.java new file mode 100644 index 00000000..2bf4c838 --- /dev/null +++ b/Problem45.java @@ -0,0 +1,36 @@ +// Time Complexity : O(N) +// Space Complexity : O(N) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : No + +class Solution { + private Map map; + private int postOrderIdx; + public TreeNode buildTree(int[] inorder, int[] postorder) { + this.map = new HashMap<>(); + this.postOrderIdx = postorder.length-1; + + for (int i = 0; i < inorder.length; i++) { + map.put(inorder[i],i); + } + + return helper(postorder, 0, inorder.length-1); + } + + private TreeNode helper(int[] postorder, int start, int end) { + //base + if (start > end) return null; + + //logic + int rootVal = postorder[this.postOrderIdx]; + int rootIdx = map.get(rootVal); + this.postOrderIdx--; + + TreeNode root = new TreeNode(rootVal); + + root.right = helper(postorder, rootIdx + 1, end); + root.left = helper(postorder, start, rootIdx - 1); + + return root; + } +} \ No newline at end of file diff --git a/Problem46.java b/Problem46.java new file mode 100644 index 00000000..8913b17e --- /dev/null +++ b/Problem46.java @@ -0,0 +1,25 @@ +// Time Complexity : O(N) +// Space Complexity : O(h) + +class Solution { + private int result; + public int sumNumbers(TreeNode root) { + this.result = 0; + helper(root, 0); + return result; + } + + private void helper(TreeNode root, int currSum) { + //base + if (root == null) return; + + //logic + currSum = currSum * 10 + root.val; + + helper(root.left, currSum); + if (root.left == null && root.right == null) { + result += currSum; + } + helper(root.right, currSum); + } +} \ No newline at end of file diff --git a/Sample.java b/Sample.java deleted file mode 100644 index f5c45b5f..00000000 --- a/Sample.java +++ /dev/null @@ -1,7 +0,0 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : - - -// Your code here along with comments explaining your approach \ No newline at end of file