Friday, May 15, 2015

Min-BST

来源:EPI

原帖:EPI 11.6 pg. 307

题目:
A min-first BST is one in which the minimum key is stored at the root; each key in the left subtree is less than every key in the right subtree. The subtress themselves are min-first BSTs. Write a function that takes a min-first BST T and a key k, and returns true iff T contains k.

代码:
 class TreeNode {  
 public:  
   int data;  
   TreeNode* left;  
   TreeNode* right;  
   TreeNode(int d) : data(d), left(NULL), right(NULL) {}  
 };  
   
   
 bool search_min_first_BST(TreeNode* r, int k) {  
   if (!r || r->data > k) {  
     return false;  
   } else if (r->data == k) {  
     return true;  
   } else if (search_min_first_BST(r->left, k)) {  
     return true;  
   }  
   return (!r->left || r->left->data < k) && search_min_first_BST(r->right, k);  
 }  

No comments:

Post a Comment