Showing posts with label BST. Show all posts
Showing posts with label BST. Show all posts

Saturday, September 20, 2014

LeetCode: Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3


   long long catalan(long long n)  
   {  
     if (n==1)return 1;  
     return ((2*(2*n-1)*catalan(n-1))/(n+1));  
   } 
 
   int numTrees(int n) {  
     if(n< 0)return 0;  
     return catalan(n);  
   }  

LeetCode: 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.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
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.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


 /**  
  * Definition for binary tree  
  * struct TreeNode {  
  *   int val;  
  *   TreeNode *left;  
  *   TreeNode *right;  
  *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
  * };  
  */  

   #define INT_MIN 0x8FFFFFFF  
   #define INT_MAX 0x7FFFFFFF  

   bool isValidBSTRecurse(TreeNode *root,int maxVal, int minVal)  
   {  
     if(!root)  
     {  
       return true;  
     }  
     if(root->val >= maxVal || root->val <= minVal)return false;  
     int x = isValidBSTRecurse(root->left,root->val, minVal);  
     int y = isValidBSTRecurse(root->right,maxVal, root->val);  
     return (x&&y);  
   }  

   bool isValidBST(TreeNode *root) {  
     int maxVal = 0x7FFFFFFF, minVal = 0x8FFFFFFF;  
     return isValidBSTRecurse(root,maxVal, minVal);  
   }