#codingexercise
Convert a binary tree to its mirror tree
Node mirror(ref node root)
{
if (root == null) return root;
els
mirror(ref node.left);
mirror(ref node.right);
temp = node.left;
node.left = node.right;
node.right = temp;
}
}
void serialize(Node root, Node delimiter, Node Empty)
{
var q = new Queue<Node>();
q.Enqueue(root);
q.Enqueue(delimiter);
var node = q.Dequeue();
while (node)
{
if (root.left)
q.Enqueue(root.left) ;
else
q.Enqueue(Empty); // new node
if (root.right)
q.Enqueue(root.right);
else
q.Enqueue(Empty); // new node
node = q.Dequeue();
Console.Write(node.toString());
if (node == delimiter) {q.Enqueue(delimiter);}
}
}
Connect nodes at the same level
Void ConnnectNodes (node root)
{
If (root == null) return;
var q = new Queue <node>();
Node prev = null;
q.Enqueue(root);
q.Enqueue(null);
var node = q.Dequeue();
while (node)
{
if (root.left)
q.Enqueue(root.left);
if (root.right)
q.Enqueue(root.right);
node = q.Dequeue();
If (prev)
Prev.nextnodeinlevel = node;
if (node == null) {
q.Enqueue(null);
prev = null;
}
}
}
#coding exercise ( one more )
Output nearest number greater than given number such that output is palindrome
int nextPalindrome(int n)
Convert a binary tree to its mirror tree
Node mirror(ref node root)
{
if (root == null) return root;
els
mirror(ref node.left);
mirror(ref node.right);
temp = node.left;
node.left = node.right;
node.right = temp;
}
}
void serialize(Node root, Node delimiter, Node Empty)
{
var q = new Queue<Node>();
q.Enqueue(root);
q.Enqueue(delimiter);
var node = q.Dequeue();
while (node)
{
if (root.left)
q.Enqueue(root.left) ;
else
q.Enqueue(Empty); // new node
if (root.right)
q.Enqueue(root.right);
else
q.Enqueue(Empty); // new node
node = q.Dequeue();
Console.Write(node.toString());
if (node == delimiter) {q.Enqueue(delimiter);}
}
}
Connect nodes at the same level
Void ConnnectNodes (node root)
{
If (root == null) return;
var q = new Queue <node>();
Node prev = null;
q.Enqueue(root);
q.Enqueue(null);
var node = q.Dequeue();
while (node)
{
if (root.left)
q.Enqueue(root.left);
if (root.right)
q.Enqueue(root.right);
node = q.Dequeue();
If (prev)
Prev.nextnodeinlevel = node;
if (node == null) {
q.Enqueue(null);
prev = null;
}
}
}
#coding exercise ( one more )
Output nearest number greater than given number such that output is palindrome
int nextPalindrome(int n)
{
for (int i =n+1; i< INT_MAX; i++)
if (isPalindrome(i)) return i;
return INT_MAX;
}
bool isPalindrome(int n)
{
var digits = n.toDigits();
int start = 0;
int end = digits.Count - 1;
while (start < end)
{
if (digits[start] != digits[end])
{
return false;
}
start++;
end--;
}
return true;
}
bool isPalindrome(int n)
{
var digits = n.toDigits();
int start = 0;
int end = digits.Count - 1;
while (start < end)
{
if (digits[start] != digits[end])
{
return false;
}
start++;
end--;
}
return true;
}
No comments:
Post a Comment