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
69 changes: 69 additions & 0 deletions Java/InsertionInBST.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// A class to store a BST node
class Node
{
int data;
Node left, right;

// Function to create a new binary tree node having a given key
Node(int key)
{
data = key;
left = right = null;
}
}

class Main
{
// Function to perform inorder traversal on the tree
public static void inorder(Node root)
{
if (root == null) {
return;
}

inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}

// Recursive function to insert a key into a BST
public static Node insert(Node root, int key)
{
// if the root is null, create a new node and return it
if (root == null) {
return new Node(key);
}

// if the given key is less than the root node,
// recur for the left subtree
if (key < root.data) {
root.left = insert(root.left, key);
}

// otherwise, recur for the right subtree
else {
// key >= root.data
root.right = insert(root.right, key);
}

return root;
}

// Function to construct a BST from given keys
public static Node constructBST(int[] keys)
{
Node root = null;
for (int key: keys) {
root = insert(root, key);
}
return root;
}

public static void main(String[] args)
{
int[] keys = { 15, 10, 20, 8, 12, 16, 25 };

Node root = constructBST(keys);
inorder(root);
}
}
32 changes: 32 additions & 0 deletions Java/mergeTwoSortedLists.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy=new ListNode();
ListNode tail=dummy;
while(list1!=null && list2!=null){
if(list1.val<list2.val){
tail.next=list1;
list1=list1.next;
tail=tail.next;
}
else{
tail.next=list2;
list2=list2.next;
tail=tail.next;
}
}
tail.next = (list1 != null) ? list1 : list2;

return dummy.next;

}
}