Saturday, March 5, 2016

LeetCode Q98: Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Solution 1:
Inorder traverse the tree and check whether all nodes visited are sorted in an ascending order.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool InOrder(TreeNode* node, long& num){
if(node==NULL)
return true;
bool r0=InOrder(node->left, num);
bool r = node->val > num;
num = node->val;
bool r1=InOrder(node->right, num);
return r0&&r&&r1;
}
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
long num=long(INT_MIN)*2;
return InOrder(root, num);
}
};
view raw Q98-1.cpp hosted with ❤ by GitHub


Solution 2:
Recursively check whether the BST properties are hold in left and right subtrees. In the meantime, we need to keep tracking the low and high bound of each side. 
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool helper(TreeNode* root, long lowBound, long highBound){
if(root==NULL)
return true;
int left=root->left==NULL? true:(root->left->val < root->val) && (root->left->val > lowBound);
int right=root->right==NULL? true:( root->right->val > root->val) && (root->right->val < highBound);
bool leftForest=helper(root->left, long(lowBound), min(long(highBound), long(root->val)));
bool rightForest=helper(root->right, max(long(lowBound), long(root->val)), long(highBound));
return left && right && leftForest && rightForest;
}
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
return helper(root, long(INT_MIN)*2, long(INT_MAX)*2); // To tackle to corner case, multiply with 2.
}
};
view raw Q98-2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment