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
47 changes: 47 additions & 0 deletions InOrderPostOrderBinaryTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* 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;
* }
* }
*/
//Time Complexity - O(n2)
//Space Complexity - O(n2)
class InOrderPostOrderBinaryTree {
public TreeNode buildTree(int[] preorder, int[] inorder) {

if (preorder.length == 0) return null;

int rootVal = preorder[0];
int rootIdx = -1;

for(int i=0; i<inorder.length; i++)
{
if(inorder[i] == rootVal)
{
rootIdx = i;
break;
}
}

int[] inorderLeft = Arrays.copyOfRange(inorder, 0, rootIdx);
int[] inorderRight = Arrays.copyOfRange(inorder, rootIdx+1, inorder.length);
int[] preorderLeft = Arrays.copyOfRange(preorder, 1, inorderLeft.length+1);
int[] preorderRight = Arrays.copyOfRange(preorder, inorderLeft.length+1, preorder.length);

TreeNode root = new TreeNode(rootVal);
root.left = buildTree(preorderLeft, inorderLeft);
root.right = buildTree(preorderRight, inorderRight);

return root;

}
}
46 changes: 46 additions & 0 deletions SumRootToLeaf
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* 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;
* }
* }
*/
//Approach: Recurse through left and right nodes and build the currSum in local scope, Add to the result at the leaf node.
//Time Complexity: O(n)
//Space Complexity: O(n)
class SumRootToLeaf {
int result;
public int sumNumbers(TreeNode root) {

helper(root, 0);
return result;
}

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

// Build the currSum
currSum = currSum * 10 + root.val;

//At leaf node add the currSum to result
if (root.left == null && root.right == null)
{
result+= currSum;
}

//Recursion
helper(root.left, currSum);

helper(root.right, currSum);
}
}