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

简介: LeetCode 235. 二叉搜索树的最近公共祖先

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

难度简单

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

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

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

image.gif 编辑

示例 1:

输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8

输出: 6

解释: 节点 2 和节点 8 的最近公共祖先是 6。

示例 2:

输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4

输出: 2

解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。

说明:

    • 所有节点的值都是唯一的。
    • p、q 为不同节点且均存在于给定的二叉搜索树中。


    思路:参考 力扣

    此题和 LeetCode:(236)剑指 Offer 68 - II. 二叉树的最近公共祖先_dreamer'~的博客-CSDN博客 类似,区别在于本题为二叉搜索树,其特性:root.Left.Val < root.Val < root.Right.Val


    时间复杂度:O(N)

    空间复杂度:O(1)

    /*** Definition for a binary tree node.* type TreeNode struct {*     Val   int*     Left  *TreeNode*     Right *TreeNode* }*/// 二叉搜索树 特性:root.Left.Val < root.Val < root.Right.ValfunclowestCommonAncestor(root, p, q*TreeNode) *TreeNode {
    // 方法1.1:迭代forroot!=nil {
    ifp.Val<root.Val&&q.Val<root.Val { // p、q都位于左子树中root=root.Left        } elseifp.Val>root.Val&&q.Val>root.Val { // p、q都位于右子树中root=root.Right        } else {
    returnroot        }
        }
    returnroot// 方法1.2:迭代// for {//     if p.Val < root.Val && q.Val < root.Val {//         root = root.Left//     } else if p.Val > root.Val && q.Val > root.Val {//         root = root.Right//     } else {//         return root//     }// }// 方法2 递归:// if p.Val < root.Val && q.Val < root.Val { // p、q都位于左子树中//     return lowestCommonAncestor(root.Left, p, q)// }// if p.Val > root.Val && q.Val > root.Val { // p、q都位于左子树中//     return lowestCommonAncestor(root.Right, p, q)// }// return root}

    image.gif


    目录
    相关文章
    |
    15天前
    Leetcode1038. 从二叉搜索树到更大和树(每日一题)
    Leetcode1038. 从二叉搜索树到更大和树(每日一题)
    |
    1月前
    leetcode热题100. 二叉树的最近公共祖先
    leetcode热题100. 二叉树的最近公共祖先
    20 0
    |
    2月前
    |
    Java
    LeetCode题解-二叉搜索树中第K小的元素-Java
    LeetCode题解-二叉搜索树中第K小的元素-Java
    13 0
    |
    3月前
    |
    算法
    代码随想录Day34 LeetCode T343整数拆分 T96 不同的二叉搜索树
    代码随想录Day34 LeetCode T343整数拆分 T96 不同的二叉搜索树
    30 0
    |
    3月前
    |
    存储 算法 测试技术
    【深度优先】LeetCode1932:合并多棵二叉搜索树
    【深度优先】LeetCode1932:合并多棵二叉搜索树
    |
    3月前
    leetcode-1382:将二叉搜索树变平衡
    leetcode-1382:将二叉搜索树变平衡
    19 0
    |
    3月前
    |
    Go
    golang力扣leetcode 96. 不同的二叉搜索树
    golang力扣leetcode 96. 不同的二叉搜索树
    16 0
    |
    3月前
    |
    Go
    golang力扣leetcode 450.删除二叉搜索树中的节点
    golang力扣leetcode 450.删除二叉搜索树中的节点
    18 0
    |
    3月前
    |
    Go
    golang力扣leetcode 95.不同的二叉搜索树II
    golang力扣leetcode 95.不同的二叉搜索树II
    22 0
    |
    3月前
    |
    Go
    golang力扣leetcode 701. 二叉搜索树中的插入操作
    golang力扣leetcode 701. 二叉搜索树中的插入操作
    16 0

    热门文章

    最新文章