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

98 Validate Binary Search Tree

时间:2015-08-19 01:59:06      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:leetcode

98 Validate Binary Search Tree

链接:https://leetcode.com/problems/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.

题目要求验证一棵树是否是二叉搜索树。来看一下二叉搜索树的定义:

(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点。

清楚了定义那么就可以开始做题,首先对于一个节点的值肯定有一个取值范围,如果是节点是父节点的左子树那么这个节点的值一定要小于父节点的值,如果这个节点存在于某个节点的右子树中那么节点的值一定要大于这个节点值。

class Solution {
public:
    bool isValidBST(TreeNode* root) 
    {
      return mValidBST(root, INT_MAX, INT_MIN);   
    }
    bool mValidBST(TreeNode* root,int max,int min)
    {
        if(root==NULL)
           return true;
        if(root->val>max||root->val<min)
            return false;
        if((root->val==INT_MIN&&root->left!=NULL)||(root->val==INT_MAX&&root->right!=NULL))
        return false;
        return mValidBST(root->left,root->val-1,min)&&mValidBST(root->right,max,root->val+1);
    }
};

还有一个做法是中序遍历树,二叉搜索树的中序遍历结果一定是个递增的数列。

class Solution {
public:
    bool isValidBST(TreeNode* root) 
    {
     vector<int> num;
     minordertraversal(root,num);
     for(int i=0;i<(int)num.size()-1;i++)
         if(num[i]>=num[i+1])
             return false;
     return true;
    }
    void minordertraversal(TreeNode* root,vector<int> &r)
    {
        if(root!=NULL)
        {
            minordertraversal(root->left,r);
            r.push_back(root->val);
            minordertraversal(root->right,r);
        }
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

98 Validate Binary Search Tree

标签:leetcode

原文地址:http://blog.csdn.net/efergrehbtrj/article/details/47767463

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