# coding exercise
Validate BST
Bool isValidBST ( node root)
{
If (root == null) return true;
If (root.left && root.left.data >= root.data ) return false;
If (root.right && root.right.data < root.data ) return false;
Return isValidBST(root.left) && isValidBST(root.right);
}
Given a singly linked list L0->L1->L2-> Ln-1-> Ln
Return interleaved L0->Ln->L1->Ln-1...
List <Node> Interleave ( List <Node> items)
{
If ( items == null || items.length <= 2) return null;
Int n = items.length;
int mid = (n%2==0) ? n/2 : n/2+1;
Var rem = root.GetRange (mid);
Int I = 1;
Int count = rem.length;
For (int k=0; k < count;k++)
{
Node last = rem.last ();
Rem.removeLast ();
Root.insertat (i, last);
I = I +2;
}
}
Node* interleave ( node* root, int n)
{
If ( root == null || n <= 2) return;
int mid = (n%2==0) ? n/2 : n/2+1;
Node* start = root;
Node* last = start->next;
while(start && last)
{
Node* prev = start;
while(last && last->next)
{
prev = last;
last = last->next;
}
prev->next = null;
Node* next = start->next;
last->next = next;
start->next = last;
start = next != null ? next->next : null;
last = (start != null) ? start->next : null;
}
}
Validate BST
Bool isValidBST ( node root)
{
If (root == null) return true;
If (root.left && root.left.data >= root.data ) return false;
If (root.right && root.right.data < root.data ) return false;
Return isValidBST(root.left) && isValidBST(root.right);
}
Given a singly linked list L0->L1->L2-> Ln-1-> Ln
Return interleaved L0->Ln->L1->Ln-1...
List <Node> Interleave ( List <Node> items)
{
If ( items == null || items.length <= 2) return null;
Int n = items.length;
int mid = (n%2==0) ? n/2 : n/2+1;
Var rem = root.GetRange (mid);
Int I = 1;
Int count = rem.length;
For (int k=0; k < count;k++)
{
Node last = rem.last ();
Rem.removeLast ();
Root.insertat (i, last);
I = I +2;
}
}
Node* interleave ( node* root, int n)
{
If ( root == null || n <= 2) return;
int mid = (n%2==0) ? n/2 : n/2+1;
Node* start = root;
Node* last = start->next;
while(start && last)
{
Node* prev = start;
while(last && last->next)
{
prev = last;
last = last->next;
}
prev->next = null;
Node* next = start->next;
last->next = next;
start->next = last;
start = next != null ? next->next : null;
last = (start != null) ? start->next : null;
}
}
No comments:
Post a Comment