LeetCode Day3
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的更多相关文章
- 【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 ...
- leetcode每日刷题计划-简单篇day3
收到swe提前批面试hhh算是ep挂了的后续 努力刷题呀争取今年冲进去! Num 21 合并两个有序链表 Merge Two Sorted Lists 注意新开的链表用来输出结果的是ListNode ...
- 我为什么要写LeetCode的博客?
# 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...
- LeetCode All in One 题目讲解汇总(持续更新中...)
终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...
- [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 ...
- 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 ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
- Leetcode 笔记 110 - Balanced Binary Tree
题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...
- Leetcode 笔记 100 - Same Tree
题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...
随机推荐
- telnet 命令使用详解
1..关于NTLM验证由于Telnet功能太强大,而且也是入侵者使用最频繁的登录手段之一,因此微软公司为Telnet添加了身份验证,称为NTLM验证,它要求Telnet终端除了需要有Telnet服务主 ...
- Struts2与ajax整合之缺点
之前有篇博客介绍了Struts2与ajax的整合,链接Struts2之-集成Json插件实现Ajax 这里不再累述,看以上博客. 此篇博客想吐槽一下Struts2的缺点--错误处理做的不好,怎么做的不 ...
- onvif规范的实现:成功实现ONVIF协议RTSP-Video-Stream与OnvifDeviceManager的视频对接
有了前几篇的基础,现在可以正式开始onvif的实现工作,其中一项非常重要的部分就是视频流的对接,即能够在符合onvif标准的监控客户端软件里接收到设备端NVT发来的RTSP视频流.这里,我所用的客户端 ...
- EntityFramework1
1.ORM都是Select * ,即使不需要某些字段,也要查询出来,效率是否很低. 可以使用视图来解决,比如对于列表页,可以定义一个视图,只查询列表中需要使用的字段,然后将列表映射为实体 2.ORM中 ...
- javascript模式——Decorator
Decorator 模式是一种结构型模式,他意在促进代码的复用,是塑造子类的一个方式. 这种想法是基于,新增的属性,对于对象来说不是必须的基本功能.我们为特殊的对象添加自己的方法,而不是重新创建一个类 ...
- (zz)Lambda 表达式(C# 编程指南)
https://msdn.microsoft.com/zh-cn/library/bb397687.aspx Lambda 表达式是一种可用于创建委托或表达式目录树类型的匿名函数.通过使用 lambd ...
- MVC和传统的以模板为中心的web架构比较
特性 以模板为中心 MVC架构 页面产生方式 运行并替换标签中的语句 由模板引擎生产HTML页面 路径解析 映射到文件系统路径,也可以通过rewrite等技术来重定向 由控制器定义,并可以通过路由系统 ...
- json 去空值与缩进
var jSetting = new Newtonsoft.Json.JsonSerializerSettings(); //忽略值为null的 jSetting.NullValueHandling ...
- mysql 取得行号后再排序
一.理论准备 Map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,Hashtable以及LinkedHashMap等. TreeMap:基于红黑树(Red-Black tre ...
- T - stl 的mapⅡ
Description Ignatius is so lucky that he met a Martian yesterday. But he didn't know the language th ...