Skip to content
Open

Tree2 #1591

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
45 changes: 45 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* 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 Problem1 {
HashMap<Integer,Integer> map;
int postOrderIdx;
public TreeNode buildTree(int[] inorder, int[] postorder) {

this.map = new HashMap<>();
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){

if(start > end) return null;

int rootVal = postorder[postOrderIdx];
int rootIdx = map.get(rootVal);
postOrderIdx--;

TreeNode node = new TreeNode(rootVal);

node.right = helper(postorder,rootIdx+1,end);
node.left = helper(postorder,start,rootIdx-1);

return node;
}
}
38 changes: 38 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* 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 Problem2 {
int result;
public int sumNumbers(TreeNode root) {
this.result = 0;
helper(root, 0);
return result;
}

private void helper(TreeNode root, int currNum){
// base case
if(root == null) return;

currNum = currNum * 10 + root.val;

helper(root.right, currNum);

if(root.left == null && root.right == null){
result += currNum;
}

helper(root.left, currNum);
}
}