Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions postorder_inorder_contruct_tree.java
Original file line number Diff line number Diff line change
@@ -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<Integer, Integer> map = new HashMap<>();
for(int i=0; i<inorder.length; i++){
map.put(inorder[i],i);
}
this.idx=postorder.length-1;
return helper(postorder,0,postorder.length-1,map);
}
private TreeNode helper(int[] postorder, int st, int end, HashMap<Integer, Integer> 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;
}
}
37 changes: 37 additions & 0 deletions sum_root_to_leaf.java
Original file line number Diff line number Diff line change
@@ -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);

}
}