leetcode Validate Binary Search Tree

来源:互联网 发布:掌上校园@学校域名 编辑:程序博客网 时间:2024/06/06 14:20

中序遍历得到所有的顺序之后只需要比较相邻的两个结点是否有序就可以了!

/**

 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode *root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(root==NULL)return true;
        TreeNode * fa = NULL;
        return solve(root,fa);
    }
private:
    bool solve(TreeNode *root,TreeNode * &fa){
        if(root==NULL)return true;
        bool ok = solve(root->left,fa);
        if(!ok)return ok;
        if(fa==NULL || fa->val<root->val){
            fa = root;
            return solve(root->right,fa);
        }else return false;
    }
};
0 0
原创粉丝点击