天天看點

[leetcode] 98. Validate Binary Search Tree 解題報告

題目連結:https://leetcode.com/problems/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. 左子樹包含的節點值都滿足小于根節點

2. 右子樹包含的節點值都滿足大于根節點

3. 左右子樹都是二叉排序樹

在本題中隻需要遞歸的周遊左右子樹即可,給定一個範圍空間,表明目前值的合法區間。需要注意的是初始的區間要超出[INT_MIN, INT_MAX]範圍,不然會無法判斷邊界的值。

代碼如下:

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