【C++】 LeetCode 98. Validate Binary Search Tree

来源:互联网 发布:godaddy创建数据库 编辑:程序博客网 时间:2024/05/18 16:16

题目:

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
Binary tree [2,1,3], return true.

Example 2:

    1   / \  2   3
Binary tree [1,2,3], return false.

解析:

二叉搜索树的中序遍历是递增序列,故考虑采用中序遍历的方式,判断是否为递增序列。由于int型为4字节,考虑可能溢出,故采用long long类型

代码:


/** * 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 forward(long long &res,TreeNode* root)    {        if(root->left!=NULL)        {            if(!forward(res,root->left))                return false;        }        if(res>=root->val)return false;        res=(long long)root->val;                if(root->right!=NULL)        {            if(!forward(res,root->right))                return false;        }        return true;    }    bool isValidBST(TreeNode* root) {        if(root==NULL)return true;        TreeNode* node=root;        while(1)        {            if(node->left!=NULL)                node=node->left;            else                break;        }        long long res=(long long)(node->val)-1;        return forward(res,root);    }};

运行结果:





0 0