File tree Expand file tree Collapse file tree 6 files changed +98
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 6 files changed +98
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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 %}
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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 %}
You can’t perform that action at this time.
0 commit comments