Monday, June 13, 2016

#some more coding exercise
Convert a binary tree to binary search tree retaining the tree structure
Solution  copy the elements by inorder traversal
Sort the array
Copy the elements back by inorder traversal

void binaryTreeToBST(Node root)
{
if (root == null) return root;
var ret = new List<int>();
store(root, ret);
ret.sort();
int i =0;
copy(root, ret, ref i)
}
void copy(node root, list<int> ret, int i)
{
if (root==null) return;
copy(root.left, ret, i);
root.data = ret[i];
i++;
copy(root.right, ret, i);
}

Print all the nodes that are a distance k from leaf
void kDistanceFromLeaf(node root,ref List<int> ancestors, int len ref List<int> result, int k)
{
if (node==null) return;
ancestors[len] = node.data;
len++;
if (node.left == null && node.right == null && len - k -1 >= 0
&& result.contains(node.data) == false){
result.add(node.data);
return;
}
kDistanceFromLeaf(root.left, ref ancestors, len ref result, k);
kDistanceFromLeaf(root.right, ref ancestors, len, ref result, k);
}

No comments:

Post a Comment