98Validate Binary Search Tree

来源:互联网 发布:招行黄金分析软件 编辑:程序博客网 时间:2024/05/16 16:11

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);        }    }};
0 0