validate-binary-search-tree

来源:互联网 发布:社交网络马克为什么渣 编辑:程序博客网 时间:2024/04/27 22:58

while写成if debug了半天。

/** * 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) {        if (!root) return true;        if(!isValidBST(root->left)) return false;        if(!isValidBST(root->right)) return false;         TreeNode* tmp,*pre;        if(root->left) {              tmp = root->left; pre=root;        while(tmp)  {            pre = tmp;            tmp =tmp->right;        }            if(pre!=root&&pre->val>=root->val) return false;           }        if(root->right) {            tmp = root->right; pre = root;          while(tmp) {               pre = tmp;               tmp = tmp->left;           }           if(pre!=root&&pre->val<=root->val) return false;        }        return true;    }};
0 0