[leetcode 98] Verify Binary Search Tree

Title: https://leetcode.cn/problems/validate-binary-search-tree/description/

insert image description here

It is very simple to do one-dimensional for the first time, and only consider the comparison between the root and the left and right subtrees when judging each recursion, which is obviously wrong.

One method is in-order traversal. The problem is that if all traversals are stored in an array, it will be too slow. I want to return immediately after finding the first non-compliant node, so I need a value to store the value of the last node. The range of tree nodes in this question is [ − 2 31 , 2 31 − 1 ] [-2^{31},2 ^{31}-1][231,2311 ] , if last is INT_MIN at the beginning, there will be problems, so long is used. Note that I use address parameter passing for last, so that the value of last can be changed in recursion.

class Solution {
    
    
public:
    bool backtracking(TreeNode* root, long& last) {
    
    
        if (!root) {
    
    
            return true;
        }
        bool left = backtracking(root->left, last);
        if (!left) {
    
    
            return false;
        }
        if (root->val <= last) {
    
    
            return false;
        }
        last = root->val;
        bool right = backtracking(root->right, last);
        if (!right) {
    
    
            return false;
        }
        return true;
        
    }
    bool isValidBST(TreeNode* root) {
    
    
        long last = LONG_MIN;
        return backtracking(root, last);
    }
};

Guess you like

Origin blog.csdn.net/weixin_43742643/article/details/128618287