在这里插入代码片
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param p int整型
* @param q int整型
* @return int整型
*/
public ArrayList<Integer> getPath(TreeNode root,int target){
ArrayList<Integer> path=new ArrayList<Integer>();
TreeNode node=root;
while(node.val!=target){
path.add(node.val);
if(target<node.val){
node=node.left;
}
if(target>node.val){
node=node.right;
}
path.add(node.val);
}
return path;
}
public int lowestCommonAncestor (TreeNode root, int p, int q) {
// write code here
ArrayList<Integer> path_p=getPath(root,p);
ArrayList<Integer> path_q=getPath(root,q);
int res=0;
for(int i=0;i<path_p.size()&&i<path_q.size();i++){
int x=path_p.get(i);
int y=path_q.get(i);
if(x==y){
res=path_p.get(i);
}
else
break;
}
return res;
}
}
在这里插入代码片
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode slow=isCircle(pHead);
if(slow==null){
return null;
}
ListNode fast=pHead;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return fast;
}
public ListNode isCircle(ListNode head){
if(head==null){
return null;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return slow;
}
} return null;
}
}