0% found this document useful (0 votes)
3 views3 pages

Adv Task5 - 0144

The document contains code solutions for two LeetCode problems: 'Unique Binary Search Trees' and 'All Elements in Two Binary Search Trees'. The first solution uses dynamic programming to calculate the number of unique BSTs that can be formed with 'n' nodes, while the second solution merges elements from two BSTs into a single sorted list using stacks. Both solutions are implemented in Java.

Uploaded by

shhreyeah30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Adv Task5 - 0144

The document contains code solutions for two LeetCode problems: 'Unique Binary Search Trees' and 'All Elements in Two Binary Search Trees'. The first solution uses dynamic programming to calculate the number of unique BSTs that can be formed with 'n' nodes, while the second solution merges elements from two BSTs into a single sorted list using stacks. Both solutions are implemented in Java.

Uploaded by

shhreyeah30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

SHREYA DHANNARAPU

VU21CSEN0100144
Task-5

1. https://leetcode.com/problems/unique-binary-search-trees/​
Code:​
class Solution {
public int numTrees(int n) {
int[] dp=new int[n+1];
Arrays.fill(dp,-1);
return helper(n,dp);
}
public int helper(int n,int[] dp){
if(n<=1) return 1;

if(dp[n]!=-1) return dp[n];


int ans=0;
for(int i=1;i<=n;i++){
ans+=(helper(n-i,dp)*helper(i-1,dp));
}
return dp[n]=ans;
}
}
Output:​


SHREYA DHANNARAPU
VU21CSEN0100144

2. https://leetcode.com/problems/all-elements-in-two-binary-search-trees/

Code:​
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
Stack<TreeNode> st1 = new Stack<>();
Stack<TreeNode> st2 = new Stack<>();

List<Integer> res = new ArrayList<>();

while(root1 != null || root2 != null || !st1.empty() || !st2.empty()){


while(root1 != null){
st1.push(root1);
root1 = root1.left;
}
while(root2 != null){
st2.push(root2);
root2 = root2.left;
}
if(st2.empty() || (!st1.empty() && st1.peek().val <= st2.peek().val)){
root1 = st1.pop();
res.add(root1.val);
root1 = root1.right;
}
else{
root2 = st2.pop();
res.add(root2.val);
root2 = root2.right;
}
}
return res;
}
}
SHREYA DHANNARAPU
VU21CSEN0100144
Output:​

You might also like