Sunday, June 12, 2016

#codingexercise
Check if a binary tree is a binary search tree
bool isBST(node root)
{
return IsBstHelper(root, INT_MIN, INT_MAX);
}

bool IsBstHelper(node root, int min, int max)
{
 if (root==null) return true;
 if (root.data < min || root.data> max) return false;
return IsBstHelper(root.left, min, root.data-1) &&
           IsBstHelper(root.right, root.data+1, max);
}

Find the largest binary tree

int GetMaxBST(node root)
{
 if (isBST(root)) return treesize(root);
 return max(GetMaxBST(root.left), GetMaxBST(root.right));
}

int GetMaxBST2(node root, ref int min, ref int max, ref int maxSize, ref bool isBST)
{
if (root == null) { isBST = true; return 0;}
int val = INT_MAX;
bool left = false;
bool right = false;
max = INT_MIN;
int lsize = GetMaxBST2(root.left, min, max, maxSize, isBST);
if (isBST && root.data > max)
    left = true;
int val = min
min = INT_MAX;
int rsize = GetMaxBST2(root.right, min,max, maxSize, isBST);
if (isBST && node.data < min)
    right = true;
if (val < min)
       min = val;
if (root.data < min)
       min = root.data;
if (root.data > max)
       max = root.data;
if (left && right)
 { if (lsize + rsize +1  > maxSize)
        maxSize = lsize+rsize+1;
    return lsize + rsize + 1;
 }
else{
   isBST = false;
   return 0;
}
}

No comments:

Post a Comment