Lowest Common Ancestor of a Binary Search Tree

 import java.util.ArrayList;
 import java.util.List;

 /**
  * LeetCode: Lowest Common Ancestor of a Binary Search Tree
  * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST
  *
  * @author LuoPeng
  * @time 215.8.5
  *
  */
 public class LowestCommonAncestor {

     /**
      * If a node A is the common ancestor, and its left child and right child are not at the same time.
      * A is the Lowest Common Ancestor
      *
      * @param root the root of the tree
      * @param p
      * @param q
      * @return lowest common ancestor (LCA) of p and q
      */
     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

         if ( root == null || p == root || q == root) {return root;}

         TreeNode lca = null;
         /*
          * If one child is null, the lowest common ancestor must be the child of the other child of root
          */
         if ( root.left == null) {
             lca = lowestCommonAncestor(root.right, p, q);
         } else if ( root.right == null) {
             lca = lowestCommonAncestor(root.left, p, q);
         } else {
             boolean first = isCommonAncestor(root.left, p, q);
             boolean second = isCommonAncestor(root.right, p, q);
             if ( first) {
                 // if root.left is a common ancestor, the LCA must be root.left or a child of it.
                 lca = lowestCommonAncestor(root.left, p, q);
             } else if (second) {
                 // if root.right is a common ancestor, the LCA must be root.right or a child of it.
                 lca = lowestCommonAncestor(root.right, p, q);
             } else {
                 // For root is a common ancestor of p and q, the LCA must be root if the left child
                 // and right child are not the common ancestors.
                 lca = root;
             }
         }

         return lca;
     }

     /**
      * Whether root is the common ancestor of p and q
      *
      * @param root a node
      * @param p a node
      * @param q a node
      * @return True if root is the common ancestor of p and q, otherwise false.
      */
     private boolean isCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
         if ( root == null) {return false;}

         TempQueue queue = new TempQueue();
         TreeNode temp = null;
         boolean first = false;
         boolean second = false;

         // Breadth First Search
         queue.push(root);
         while ( !queue.empty()) {
             temp = queue.peek();
             queue.pop();
             if ( temp ==p) {
                 first = true;
             } else if ( temp == q) {
                 second = true;
             }
             // add the child
             if ( temp.left != null) {
                 queue.push(temp.left);
             }
             if ( temp.right != null) {
                 queue.push(temp.right);
             }
             // break if p and q have bean found
             if ( first && second) {
                 break;
             }
         }

         return first && second;
     }

 }

 /**
  * Queue
  *
  */
 class TempQueue {
     public void push(TreeNode x) {
         values.add(x);
     }

     public void pop() {
         values.remove(0);
     }

     public TreeNode peek() {
         return values.get(0);
     }

     public int size() {
         return values.size();
     }

     public boolean empty() {
         return values.size()==0;
     }

     private List<TreeNode> values = new ArrayList<TreeNode>();
 }

LeetCode Day3的更多相关文章

  1. 【LeetCode算法题库】Day3:Reverse Integer & String to Integer (atoi) & Palindrome Number

    [Q7]  把数倒过来 Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Outpu ...

  2. leetcode每日刷题计划-简单篇day3

    收到swe提前批面试hhh算是ep挂了的后续 努力刷题呀争取今年冲进去! Num 21 合并两个有序链表 Merge Two Sorted Lists 注意新开的链表用来输出结果的是ListNode ...

  3. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  4. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  5. [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  6. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  7. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  8. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  9. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

随机推荐

  1. Unity 音乐播放全局类

    今天晚了LOL, 发现里面的声音系统做得很不错,于是最近就写了一份反正以后也用的到,2D音乐全局播放. 项目跟PoolManager对象池插件结合了. 解决的问题: 1. 已经播放的声音,可以马上暂停 ...

  2. Phoenix中Sequence的用法

    Phoenix--HBase的JDBC驱动 序列(Sequence)是Phoenix提供的允许产生单调递增数字的一个SQL特性,序列会自动生成顺序递增的序列号,以实现自动提供唯一的主键值.   使用C ...

  3. java值传递

    Java使用按值传递的函数调用方式,这往往使我感到迷惑.因为在基础数据类型和对象的传递上,我就会纠结于到底是按值传递,还是按引用传递.其实经过学习,Java在任何地方,都一直发挥着按值传递的本色. 首 ...

  4. MyEclipse 注册码

    MyEclipse 注册码和大家共享一下! 一:MyEclipse_6.0.1GA_E3.3.1_FullStackInstaller注册码 Subscriber:javp Subscription ...

  5. UILabel + 导入字体

    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 100)]; 1.设置文字颜色 label.textC ...

  6. php不区分大小写

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  7. java菜鸟篇<二> eclipse启动tomcat报错的问题:Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"

    9.1今天不知道自己瞎搞eclipse的时候按到了什么键,然后再启动程序的时候就会报错: 如下: Exception: java.lang.OutOfMemoryError thrown from t ...

  8. MySql小知识点

    1.查看MySql是什么编码 show create table tablename;

  9. Windows 下 Apache HTTP Server 安装、配置以及与 Tomcat 的整合(附图)

    如果您能点开这篇文章,说明您已对熟悉Apache HTTP Server(下文用Apache简称)配置的重要性已很清楚了,本文不在赘述,直接介入正题,请往下阅读: 为便于阅读,列出文章目录: 一.Ap ...

  10. Android sample 之模拟重力感应,加速度

    class SimulationView extends View implements SensorEventListener { // diameter of the balls in meter ...