zoukankan      html  css  js  c++  java
  • 代码题(10)— 验证二叉搜索树、二叉搜索树的最近公共祖先

    1、98. 验证二叉搜索树

    给定一个二叉树,判断其是否是一个有效的二叉搜索树。

    一个二叉搜索树具有如下特征:

    • 节点的左子树只包含小于当前节点的数。
    • 节点的右子树只包含大于当前节点的数。
    • 所有左子树和右子树自身必须也是二叉搜索树。

    示例 1:

    输入:
        2
       / 
      1   3
    输出: true
    /**
     * 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 BSTcore(root, LONG_MIN, LONG_MAX);
        }
         bool BSTcore(TreeNode *root, long min, long max) {
            if (!root) 
                return true;
            if (root->val <= min || root->val >= max) 
                return false;
            return BSTcore(root->left, min, root->val) && BSTcore(root->right, root->val, max);
        }
    };

    2、235. 二叉搜索树的最近公共祖先

    给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

    百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

    例如,给定如下二叉搜索树:  root = [6,2,8,0,4,7,9,null,null,3,5]

            _______6______
           /              
        ___2__          ___8__
       /              /      
       0      _4       7       9
             /  
             3   5
    

    示例 1:

    输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
    输出: 6 
    解释: 节点 2 和节点 8 的最近公共祖先是 6。
    /**
     * 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)
                return nullptr;
            if(root->val > max(p->val, q->val))
                return lowestCommonAncestor(root->left, p, q);
            else if(root->val < min(p->val, q->val))
                return lowestCommonAncestor(root->right, p, q);
            else 
                return root;
            
            
        }
    };
  • 相关阅读:
    Response.Status http协议状态代码
    ASP.NET MVC 如何实现头压缩
    Google PR值原理和详细解说
    NodeJS 深入浅出
    C#: ToString格式
    HttpHandler实现媒体文件和图像文件的盗链(防盗链设计)
    ASP.NET MVC 使用Areas功能的常见错误
    VC中利用多线程技术实现线程之间的通信
    基于Visual C++的Winsock API研究
    键盘钩子程序
  • 原文地址:https://www.cnblogs.com/eilearn/p/9219112.html
Copyright © 2011-2022 走看看