LeetCode#98. Validate Binary Search Tree

topic:

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

Analysis of the meaning of the question: This question is to judge whether it is a binary search tree given a tree. We all know that the in-order traversal of the binary search tree is a sequence from small to large. We can output the in-order traversal and judge Whether it is an ascending sequence is enough, or it can be judged while traversing, which can greatly save time, so the method of judging in traversal is adopted.
A C++ implementation is as follows:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
class Solution {
public:
    bool first = true;
    int last_value;
    bool isValidBST(TreeNode* root) {
        if(root == NULL){
            return true;
        }
        return isValidBST(root->left) && Comparison(root->val) &&isValidBST(root->right);
    }
    bool Comparison(int val) {
        if(first) {
            first = false;
            last_value = val;
            return true;
        }
        if(val <= last_value) return false;
        last_value = val;
        return true;
    }
};


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325402509&siteId=291194637