1305. All Elements in Two Binary Search Trees ( Leetcode Problem )

preview_player
Показать описание
@CodeChef @GeeksforGeeks @Leetcodes #leetcode #geeksforgeeks #adobe #amazon #microsoft #dailychallenge #technicalinterview #problemoftheday

Solution Code: Available in comment section

Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.
Рекомендации по теме
Комментарии
Автор

Solution Code:
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
List<Integer> al1=new ArrayList<>();
List<Integer> al2=new ArrayList<>();
inorder(root1, al1);
inorder(root2, al2);
List<Integer> ans=new ArrayList<>();
int i=0, j=0;
while(i<al1.size() && j<al2.size())
{
if(al1.get(i)<al2.get(j))
{
ans.add(al1.get(i));
i++;
}
else
{
ans.add(al2.get(j));
j++;
}
}
while(i<al1.size())
{
ans.add(al1.get(i));
i++;
}
while(j<al2.size())
{
ans.add(al2.get(j));
j++;
}
return ans;
}
static void inorder(TreeNode root, List<Integer> al)
{
if(root==null) return ;

inorder(root.left, al);
al.add(root.val);
inorder(root.right, al);
}
}

viralSongsBollywood
Автор

Please help me out..
After understanding the question I wrote the solution code but one of the Test Case didn't pass :( I and tried a lot to find the require change in my code but still unable to understand where the problem is.
Test case :
[ ]
[5, 1, 7, 0, 2]

Solution Code:
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
List<Integer> first = new ArrayList<>();
List<Integer> second = new ArrayList<>();
List<Integer> mergedList = new ArrayList<>();
// Getting the elements/nodes of tree inOrder hence ascending sorted order
inOrder(root1, first);
inOrder(root2, second);

merge(first, second, mergedList);

return mergedList;
}

public void merge(List<Integer> first, List<Integer> second, List<Integer> mergeList){
int i=0, j=0;

while(i<first.size() && j<second.size()){

mergeList.add(first.get(i));
i++;
}else{

j++;
}
}

while(i<first.size()){
mergeList.add(first.get(i));
i++;
}
while(j<second.size()){

j++;
}
}

public void inOrder(TreeNode root, List<Integer> a){
if(root == null){
return;
}
inOrder(root.left, a);
a.add(root.val);
inOrder(root.right, a);
}
}

aniketsingh
welcome to shbcf.ru