题目描述
题目链接: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.
例子
例子 1
Input:
[2,1,3]
Output:true
例子 2
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.
解题思路
要做这道题首先要知道二叉搜索树和前序遍历的关系,假定一棵二叉搜索树是合法的,那么用前序遍历可以将所有节点从小到大输出。那么要判断一棵树是不是合法的二叉树搜索树,只需要通过前序遍历过程中判断前一个节点值是否小于后一个节点值即可,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include <limits.h>
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (root == nullptr) return true;
if (!isValidBST(root->left)) return false;
if (prev_val >= root->val && !is_first) return false;
prev_val = root->val;
is_first = false;
return isValidBST(root->right);
}
private:
int prev_val = INT_MIN;
bool is_first = true; // 用一个布尔值表示是否第一个节点
};
- 时间复杂度: O(n)
- 空间复杂度: O(h) – 遍历深度
GitHub 代码同步地址: 98.ValidateBinarySearchTree.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions