码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 98. Validate Binary Search Tree

时间:2015-02-18 11:45:52      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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、递归

bool isValidBST(TreeNode *root) 
    {
        return BSTCheck(root, (long long)INT_MIN - 1, (long long)INT_MAX + 1);
    }
    
    bool BSTCheck(TreeNode *root, long long left, long long right)
    {
        if (root == NULL)
            return true;
        return ((long long)root->val > left) && ((long long)root->val < right) 
            && BSTCheck(root->left, left, root->val)
            && BSTCheck(root->right, root->val, right);
    }

2、根据BST的性质,中序遍历结果递增

 1 bool isValidBST(TreeNode *root) 
 2     {
 3         vector<int> vtree;
 4         
 5         if (root == NULL)
 6             return true;
 7         
 8         inorder(root, vtree);
 9         for (int i = 0; i < vtree.size() - 1; i++)
10         {
11             if (vtree[i] >= vtree[i + 1])
12                 return false;
13         }
14         return true;
15     }
16     
17     void inorder(TreeNode *root, vector <int> &ret)
18     {
19         if (root == NULL)
20             return;
21         inorder(root->left, ret);
22         ret.push_back(root->val);
23         inorder(root->right, ret);
24     }

leetcode 98. Validate Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4295694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!