class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null || root==p || root==q){
return root;
}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left==null){
return right;
}
if(right==null){
return left;
}
return root;
}
}
带next指针指向父节点的LCA问题 思路:得到p、q为头节点的两个链表,求链表的公共节点
Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
TreeNode next; //指向父节点
* TreeNode(int x) { val = x; }
* }
class Solution {
public TreeNode lowestCommonAncestor(TreeNode p, TreeNode q) {
TreeNode phead = p;
TreeNode qhead = q;
int plength = 0;
int qlength = 0;
while(phead.next!=null){
plength++;
phead = phead.next;
}
while(qhead.next!=null){
qlength++;
qhead = qhead.next;
}
int len = plength - qlength;
TreeNode fast = p;
TreeNode slow = q;
if(len<0){
fast = q;
slow = p;
}
for(int i=0; i<len; i++){
fast = fast.next;
}
while(fast.next!=null && slow.next!=null && fast.val!=slow.val){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}