[Leetcode]98. Validate Binary Se

2019-08-17  本文已影响0人  木易yr

98. 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.

Example 1:

   2
   / \
  1   3

Input: [2,1,3]
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false

Explanation: The root node's value is 5 but its right child's value is 4.

题意:验证二叉搜索树
思路1:一开始的范围是负无穷到正无穷,然后自上而下根据范围递归判断是否满足所有的左子树都小于根结点,右子树都大于根结点

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        return dfs(root,INT_MIN,INT_MAX);
    }
    bool dfs(TreeNode*root,long long minv,long long maxv)
    {
        if(root==NULL)
        return true;
        if(root->val<minv||root->val>maxv)
        return false;
        return  dfs(root->left,minv,root->val-1ll) && dfs(root->right,root->val+1ll,maxv);
    }
};

为什么使用long long ?
因为:一开始是边界负无穷,减一会溢出,所以必须用long long
思路2:判断中序遍历是否递增

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int>v;
    bool isValidBST(TreeNode* root) {
       if(root==NULL||(root->left==NULL && root->right==NULL)) 
           return true;
        inorder(root);
        for(int i=1;i<v.size();i++)
            if(v[i]<=v[i-1])
                return false;
        return true;
        }
    void inorder(TreeNode* root){
        if(root==NULL)
            return ;
        inorder(root->left);
        v.push_back(root->val);
        inorder(root->right);
    }
};
上一篇 下一篇

猜你喜欢

热点阅读