98. 验证二叉搜索树

xiaoxiao2021-03-01  6

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

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

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

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

示例 2:

输入: 5 / \ 1 4 / \ 3 6 输出: false

解释: 输入为: [5,1,4,null,null,3,6]。 根节点的值为 5 ,但是其右子节点值为 4 。 法一:利用本身性质解决

/** * 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 valid(root, LONG_MIN, LONG_MAX); } bool valid(TreeNode* root, long minVal, long maxVal) { if(!root) return true; if(root->val <= minVal || root->val >= maxVal) { return false; } return valid(root->left, minVal, root->val) && valid(root->right, root->val, maxVal); } };

法二:由于题中做了要求,左<根<右,所以对二叉树进行中序遍历,若所得序列为升序序列,自然符合题意

/** * 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) { if(!root) { return true; } vector<int> res; inorder(root, res); for(int i = 0; i < res.size() - 1; i++) { if(res[i] >= res[i + 1]) { return false; } } return true; } void inorder(TreeNode* root, vector<int>& res) { if(!root) { return; } inorder(root->left, res); res.push_back(root->val); inorder(root->right, res); } };
转载请注明原文地址: https://www.6miu.com/read-3350271.html

最新回复(0)