Saturday, May 11, 2013

Validate binary search tree(C++ code)

LeetCode Validate Binary Search Tree, Aug 31 '12
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.
思路:这题简单,一次bug free。。。最近都在科普python,sql ,为了避免C++手生,决定每天练一道leetcode,恩,发现C还是很重要的,把C搞懂了,学其他的才会事半功倍~
  1. #helper function  
  2. bool isValidBST(TreeNode *root, int lower, int upper){  
  3.   
  4.  if (!root) return true;  
  5.   
  6.  if(root->val <= lower || root->val >= upper) return false;  
  7.   
  8.  bool left = isValidBST(root->left, lower, root->val);  
  9.   
  10.  bool right = isValidBST(root->right, root->val, upper);  
  11.   
  12.    
  13.   
  14.  return left && right;  
  15.   
  16. }  
  17.   
  18. bool isValidBST(TreeNode *root) {  
  19.         isValidBST(root, INT_MIN, INT_MAX);  
  20.          
  21.     }   

No comments:

Post a Comment