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: Recursion. 1. Add lower & upper bound. O(n)
2. Inorder traversal with one additional parameter (value of predecessor). O(n)

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isValidBST(TreeNode *root) {
13         int val = INT_MIN;
14         return isValidBSTRe(root, val);
15     }
16     
17     bool isValidBSTRe(TreeNode* root, int& val)
18     {
19         if(!root) return true;
20         
21         if(root->left && !isValidBSTRe(root->left, val))
22             return false;
23         if(root->val <= val) 
24             return false;
25         val = root->val;
26         if(root->right && !isValidBSTRe(root->right, val))
27             return false;
28         return true;
29     }
30 };

 

posted @ 2014-04-07 02:18  beehard  阅读(102)  评论(0编辑  收藏  举报