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. 数据库的优化tips

    数据库   TIPS:: 1.用于记录或者是数据分析的表创建时::使用Id作为主键,1,2,3...表示消息条数.用户账号id用于做外键.一个用户相应唯一个accountId             ...

  2. 设置Android设备在睡眠期间始终保持WLAN开启的代码实现

    MainActivity例如以下: package cc.ab; import android.os.Bundle; import android.provider.Settings; import ...

  3. 加载本地html遇到的问题

    之前要做一个Demo,需要用UIWebView来加载网页,前端的同事把资源包给我,里面包含html,css,JavaScript,图片等文件.我想当然的把文件夹拷到工程中,然后用以下方法加载: NSU ...

  4. 浅谈postMessage多页面监听事件

    最近做了一个Echarts和Highcharts多图多页面连动的效果,就用到postMessage 如下介绍: 最开始在最外围的页面也就是所有页面的父级页面添加postMessage监听事件以便监听下 ...

  5. BlazeDS简介(转自openkk的日志)

    BlazeDS 是一个基于服务器的 Java 远程控制 (remoting) 和 Web 消息传递 (messaging) 技术,以LGPL(Lesser GNU Public License)公共许 ...

  6. HDU 1055 - Color a Tree

    一棵树,结点树为n,根结点为r.每个结点都有一个权值ci,开始时间为0,每染色一个结点需要耗时1,每个结点的染色代价为ci*ti(ti为当前的时间),每个结点只有在父结点已经被染色的条件下才能被染色. ...

  7. [?]Unity快捷键

    Super=Win键. Rererence: What are Unity's keyboard and mouse shortcuts?

  8. Windows 端口和任务 查看 相关命令

    netstat -aon|findstr " //查看端口 tasklist|findstr " //根据PID找到对应的程序 taskkill /f /t /im netbox. ...

  9. 【Android类型SDK测试(一)】认识Android类型的 SDK

    (一)SDK是个什么东东 接触软件相关行业的同学都应该知道,SDK(即 Software Development Kit),软件开发包.其作用就是为开发某些软件提供一些便利的东西,包括工具 集合,文档 ...

  10. mac/linux install hg

    MAC OSX 10.9: sudo port -v install mercurial or easy_install mercurial