1. 程式人生 > >98. Validate Binary Search Tree (Tree)

98. Validate Binary Search Tree (Tree)

題目連結:https://leetcode.com/problems/validate-binary-search-tree/

題目描述:判斷BST是否合法。

思路:中序遍歷;對於BST來說,中序遍歷的結果是一個遞增的序列,所以在遞增的過程中判斷即可。

程式碼:

class Solution {
public:
    void order(TreeNode *root){
         if(!root || ret == 0) return;
        
         order(root->left);
        
         if(start&&root->val <= val) ret = 0;
         if(!start) start = 1;
        
         val = root->val;
         order(root->right);
    }
    bool isValidBST(TreeNode* root) {
         start = 0;
         ret = 1;
         order(root);
         return ret;
    }
private:
    int   val;
    bool  ret;
    bool  start;
};