zoukankan      html  css  js  c++  java
  • Lowest Common Ancestor of Binary (Search) Tree

    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.

    思路:找A与B的LCA,有两种可能  1. A或B是另一个点得祖先。比如3,2的LCA就是2。

                    2. 一个TreeNode,它的左右子树一个包含A,一个包含B。

       这种思路是对于binary tree与binary search tree都适用的,还有一种方法,利用了BST得特点,通过对数值的运算确定了,这个LCA是在root的左子树还是右子树,还是root本身。在leetcode的disscusion中有人提到了。两种的代码如下:

     1 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
     2         if (root == null || root == p || root == q) {
     3             return root;
     4         }
     5         TreeNode left = lowestCommonAncestor(root.left, p, q);
     6         TreeNode right = lowestCommonAncestor(root.right, p, q);
     7         
     8         if (left != null && right != null) {
     9             return root;
    10         }
    11         if (left != null) {
    12             return left;
    13         }
    14         if (right != null) {
    15             return right;
    16         }
    17         return null;
    18 }
    1 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    2         while((root.val - p.val) * (root.val - q.val) > 0) {
    3             root = (root.val - p.val) > 0 ? root.left : root.right;
    4         }
    5         return root;
    6 }
  • 相关阅读:
    php中防止SQL注入的方法
    谈谈asp,php,jsp的优缺点
    SSH原理与运用(一):远程登录
    优化MYSQL数据库的方法
    json_encode和json_decode区别
    静态方法与非静态方法的区别
    Java 异常的Exception e中的egetMessage()和toString()方法的区别
    $GLOBALS['HTTP_RAW_POST_DATA'] 和$_POST的区别
    HTML5开发,背后的事情你知道吗?
    使用C语言来实现模块化
  • 原文地址:https://www.cnblogs.com/gonuts/p/4639904.html
Copyright © 2011-2022 走看看