leetcode中的一些二分搜索树

235(最近公共祖先)

/**
 * 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:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root==NULL)
            return 0;
        
        if(p->val<root->val&&q->val<root->val)
            return lowestCommonAncestor(root->left,p,q);
        if(p->val>root->val&&q->val>root->val)
            return lowestCommonAncestor(root->right,p,q);
        return root;
    }
};

236(任意二叉树,不是二叉搜索树)

98(验证是否为二叉搜索树)

法一:直接采用自身性质,左<中<右

/**
 * 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) {
        return isValidBST(root,LONG_MIN,LONG_MAX);
    }
    
    bool isValidBST(TreeNode *root,long mn,long mx){
        if(!root) return true;
        if(root->val<=mn||root->val>=mx) return false;
        return isValidBST(root->left,mn,root->val)&&isValidBST(root->right,root->val,mx);
    }
};

法二:采用中序遍历来验证

/**
 * 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 isPre = false;
    int pre = -1;
    
    bool isValidBST(TreeNode* root) {
        return inOrder(root);
    }
    
    bool inOrder(TreeNode* node){
        if(node == NULL)
            return true;

        if(!inOrder(node->left))
            return false;

        if(isPre && pre >= node->val)
            return false;
        
        isPre = true;
        pre = node->val;

        if(!inOrder(node->right))
            return false;

        return true;
    }
};

450

108

230

236(任意二叉树,不是二叉搜索树)

原文地址:https://www.cnblogs.com/darklights/p/11721991.html