• 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(任意二叉树,不是二叉搜索树)

  • 相关阅读:
    头文件#ifndef #define #endif使用
    Django框架【form组件】
    数据库【mysql】之pymysql
    数据库【mysql篇】典型的一些练习题目
    Python开发【socket篇】解决粘包
    Python开发【内置模块篇】os模块
    Python开发【内置模块篇】日志模块
    Python开发【内置模块篇】configparser
    Python开发【内置模块篇】collections
    Python开发【内置模块篇】datetime
  • 原文地址:https://www.cnblogs.com/darklights/p/11721991.html
Copyright © 2020-2023  润新知