Skip to content

Commit 84277f5

Browse files
committed
add lca of bst and pal linked list
1 parent 686aa05 commit 84277f5

File tree

6 files changed

+98
-0
lines changed

6 files changed

+98
-0
lines changed

lowest-common-ancestor-of-a-binary-search-tree/README.md

Whitespace-only changes.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
public class Solution {
11+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
12+
// make sure p < q
13+
if(p.val > q.val) return lowestCommonAncestor(root, q, p);
14+
15+
// find p <= root <= q
16+
while(!(p.val <= root.val && root.val <= q.val)){
17+
18+
if(root.val > q.val){
19+
root = root.left;
20+
} else { // root.val < p.val
21+
root = root.right;
22+
}
23+
24+
}
25+
26+
return root;
27+
}
28+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
layout: solution
3+
title: Lowest Common Ancestor of a Binary Search Tree
4+
date: 2015-07-12 16:47:16+08:00
5+
leetcode_id: 235
6+
---
7+
{% include_relative README.md %}

palindrome-linked-list/README.md

Whitespace-only changes.

palindrome-linked-list/Solution.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
public class Solution {
10+
ListNode mid(ListNode head){
11+
12+
ListNode fast = head;
13+
ListNode slow = head;
14+
15+
while(fast != null && fast.next != null){
16+
fast = fast.next.next;
17+
slow = slow.next;
18+
}
19+
20+
return slow;
21+
}
22+
23+
ListNode reverse(ListNode head) {
24+
ListNode prev = null;
25+
26+
while(head != null){
27+
28+
ListNode t = head.next;
29+
30+
head.next = prev;
31+
prev = head;
32+
33+
head = t;
34+
}
35+
36+
return prev;
37+
}
38+
39+
public boolean isPalindrome(ListNode head) {
40+
ListNode m = mid(head);
41+
42+
m = reverse(m);
43+
44+
while(m != head && m != null){
45+
46+
if(m.val != head.val){
47+
return false;
48+
}
49+
50+
m = m.next;
51+
head = head.next;
52+
}
53+
54+
return true;
55+
}
56+
}

palindrome-linked-list/index.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
layout: solution
3+
title: Palindrome Linked List
4+
date: 2015-07-12 17:00:15+08:00
5+
leetcode_id: 234
6+
---
7+
{% include_relative README.md %}

0 commit comments

Comments
 (0)