LeetCode98. Validate Binary Search Tree Add to List

来源:互联网 发布:淘宝客订单部分退款 编辑:程序博客网 时间:2024/06/06 01:16

解题思路:根据二叉查找树的定义,中序遍历二叉树得到的序列应该是一个增序列,所以使用中序遍历

/** * 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 {    vector<int>res;  public:    bool isValidBST(TreeNode* root) {        if(root==NULL) return true;        if(root->left ==NULL && root->right==NULL)return true;        Inorder(root);        for(int i= 1;i < res.size();i++){            if (res[i] <= res[i-1]) return false;          }        return true;    }    void Inorder(TreeNode* root){        if(root==NULL)return;        Inorder(root->left);        res.push_back(root->val);        Inorder(root->right);    }};


0 0
原创粉丝点击