leetcode-98. 验证二叉搜索树

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

一个二叉搜索树具有如下特征:

  • 节点的左子树只包含小于当前节点的数。
  • 节点的右子树只包含大于当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

示例 1:

输入:
    2
   / \
  1   3
输出: true

示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

解题思路:

直接中序遍历。

class Solution {//中序遍历递增
public:
    bool flag=true;
    int minV=-123654123;
    int cnt=0;
    bool isValidBST(TreeNode* root) {
        if(root==NULL)
            return true;
        inOrder(root);
        return flag;
    }
    void inOrder(TreeNode* root)
    {
        if(root==NULL)
            return;
        if(root->left)
            inOrder(root->left);
        cnt++;
        if(cnt==1)
        {
            minV=root->val;
        }
            
        else
        {
          if(root->val<=minV)
          {
            flag=false;
            return;
          }
          else
          {
             minV=root->val;
          }    
        }
        if(root->right)
            inOrder(root->right);
    }
   
};

猜你喜欢

转载自blog.csdn.net/zhuixun_/article/details/80489430
今日推荐