zoukankan      html  css  js  c++  java
  • LC.235.Lowest Common Ancestor of a Binary Search Tree

    https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

    According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

    _______6______
    /
    ___2__ ___8__
    / /
    0 _4 7 9
    /
    3 5
    For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6.
    Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
    像这种返回一个node 的东西,结果要不就从左边来, 要不就从右边来,否则就是null
    凡事遍历的点,先查一下自己满足不满足,不满足的话,稍微pruning 一下,大胆往左右两边丢,然后等答案返回来
    check bal. tree height, path sum i 都是这样

     1 // the goal is to find the root that would sit in the middle
     2     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
     3         //base case
     4         if (root == null) return null ;
     5         int min = Math.min(p.val, q.val) ;
     6         int max = Math.max(p.val, q.val) ;
     7         //pre order:看看当前点是不是满足的值
     8         if (root.val>=min && root.val <= max) return root ;
     9         //the left: branch pruning > max, then go left: 左边返回就一层层往上返回
    10         if (root.val > max){
    11            return lowestCommonAncestor(root.left, p, q) ;
    12         }
    13         //the right: branch pruning: <min: then go right: 右边返回就一层层往上返回
    14         if (root.val < min){
    15           return lowestCommonAncestor(root.right, p, q) ;
    16         }
    17         //不从左边,也不从右边的话,就是NULL
    18         return null;
    19     }

    这道题首先要明确题目背景---二叉搜索树。也正是因为是二叉搜索树,所以我们可以利用二叉搜索树从小到大排好序的特性来做。

    对于一个root和另外两个Node来说,它们的值会有以下几种情况:

    1. root.val < p.val && root.val < q.val 此时,两个node的值都比root大,说明这两个值在root右边的subtree里,且他们的最小公共顶点不可能是当前root

    2. root.val > p.val && root.val > q.val 此时,两个node的值都比root小,说明这两个值在root左边的subtree里,且他们的最小公共顶点不可能是当前root

    3. else,此时 root的值在p,q之间(或等于p,q中的某一个),此时,当前root即为公共顶点



  • 相关阅读:
    js 修改 title keywords description
    添加第一次进入网站动画
    懒加载
    一些正则
    对图片进行剪切,保留原始比例
    JS判断是否是微信页面,判断手机操作系统(ios或android)并跳转到不同下载页面
    判断网页是否再微信内置浏览器打开
    数字转汉字大写
    java 反射机制 之 getConstructor获取有参数构造函数 然后newInstance执行有参数的构造函数
    web实训项目(快递e栈)-----04项目实现的基本流程
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8495924.html
Copyright © 2011-2022 走看看