ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode 98 Validate Binary Search Tree DFS

2022-05-16 06:31:25  阅读:37  来源: 互联网

标签:node Binary Search right TreeNode val Tree root left


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;
    }
    
};


标签:node,Binary,Search,right,TreeNode,val,Tree,root,left
来源: https://www.cnblogs.com/xinyu04/p/16275558.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有