LeetCode 98 Validate Binary Search Tree DFS

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid 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.

Solution

\(BST\) 满足对于中序遍历,得到的节点值为递增序列。所以先中序遍历以后,检查序列是否严格递增即可:

点击查看代码
/**  * 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) {}  * };  */ class Solution { private:     vector<int> node;          void dfs(TreeNode* root){         if(!root) return;         dfs(root->left); node.push_back(root->val); dfs(root->right);     } public:     bool isValidBST(TreeNode* root) {         if(root==NULL) return true;         dfs(root);         int n = node.size();         for(int i=1;i<n;i++){             if(node[i-1]>=node[i])return false;         }         return true;     }      };