Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Saturday, June 10, 2017

Is This a BST solution



The Node class is defined as follows:
    class Node {
        int data;
        Node left;
        Node right;
     }
*/
Idea is to traverse through left and right node and checks whether it is satisfying the property of BST and compare value with parent and upper than parents node also.


   boolean left(Node root, int pdata) {
    if (root == null) return true;
    if (root.data >= pdata) return false;
    return left(root.left, root.data) &&
        left(root.left, pdata) &&
        left(root.right, pdata) &&
        right(root.right, root.data);
}

boolean right(Node root, int pdata) {
    if (root == null) return true;
    if (root.data <= pdata) return false;
    return right(root.right, root.data) &&
        right(root.right, pdata) &&
        right(root.left, pdata) &&
        left(root.left, root.data);
}

boolean checkBST(Node root) {
return left(root.left, root.data) &&
    right(root.right, root.data);
}

0 Comments:

Post a Comment

Stats