LeetCode(98) Validate Binary Search Tree

来源:互联网 发布:js 鼠标点击后div移动 编辑:程序博客网 时间:2024/05/16 05:57

递归算法,确定函数功能及与功能对应的接口。

代码如下:

/** * 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:    vector<int> recursion(TreeNode *root) {        if(root->left == NULL && root->right == NULL) {            vector<int> result(3, 0);            result[0] = 1;            result[1] = root->val;            result[2] = root->val;            return result;        }        vector<int> result(3, 0);        if(root->left != NULL && root->right != NULL) {            vector<int> tmpLeft;            tmpLeft = recursion(root->left);            vector<int> tmpRight;            tmpRight = recursion(root->right);            if((tmpLeft[0] == 0) || (tmpRight[0] == 0)) {                result[0] = 0;                return result;            }else{                if(tmpLeft[1] >= root->val || tmpRight[2] <= root->val) {                    result[0] = 0;                    return result;                }else {                    result[0] = 1;                    result[1] = tmpRight[1];                    result[2] = tmpLeft[2];                    return result;                }            }        }        if(root->left != NULL && root->right == NULL) {            vector<int> tmpLeft;            tmpLeft = recursion(root->left);            if(tmpLeft[0] == 0) {                result[0] = 0;                return result;            }else {                if(tmpLeft[1] >= root->val) {                    result[0] = 0;                    return result;                }else {                    result[0] = 1;                    result[1] = root->val;                    result[2] = tmpLeft[2];                    return result;                }            }        }        if(root->left == NULL && root->right != NULL) {            vector<int> tmpRight;            tmpRight = recursion(root->right);            if(tmpRight[0] == 0) {                result[0] = 0;                return result;            }else {                if(tmpRight[2] <= root->val) {                    result[0] = 0;                    return result;                }else {                    result[0] = 1;                    result[1] = tmpRight[1];                    result[2] = root->val;                    return result;                }            }        }    }    bool isValidBST(TreeNode* root) {        if(root == NULL)            return true;        return recursion(root)[0] == 0 ? false : true;    }};
0 0