Leetcode 98验证二叉搜索树 C++

思路:将二叉树中序遍历一遍,将结果存储在一个数组中,然后判断该数组是否是升序排列即可。

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

猜你喜欢

转载自blog.csdn.net/qq_43387999/article/details/87809244
今日推荐