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即为公共顶点



  • 相关阅读:
    stl 在 acm中的应用总结
    hdu_2089(数位dp)
    水dp第二天(背包有关)
    dp水一天
    poj_2195Going Home(最小费用最大流)
    poj_3281Dining(网络流+拆点)
    GSS4
    SPOJ GSS1_Can you answer these queries I(线段树区间合并)
    Ajax实现局部数据交互的一个简单实例
    对学习Ajax的知识总结
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8495924.html
Copyright © 2011-2022 走看看