# 二叉树两个节点的最近公共祖先问题

CSDN：二叉树两个节点的最近公共祖先问题

## 题目描述

    public static class Info {
public Info(boolean findA, boolean findB, TreeNode ancestor) {
this.findA = findA;
this.findB = findB;
this.ancestor = ancestor;
}
private boolean findA;
private boolean findB;
private TreeNode ancestor;

}


findA表示能否在当前(子)树下找到 a 节点；

findB表示能否在当前(子)树下找到 b 节点；

ancestor表示当前两个节点的最低公共祖先是什么。

if (a == null) {
// a 为 null，不管 b 是否为 null，公共祖先都是 b
return b;
}
if (b == null) {
// b 为 null， 不管 a 是否为 null，公共祖先都是 a
return a;
}


Info p(TreeNode head, TreeNode a, TreeNode b)


        if (head == null) {
return new Info(false, false, null);
}


// 左树收集信息
Info leftInfo = p(head.left, a, b);
// 右树收集信息
Info rightInfo = p(head.right, a, b);

// 整合
......


findB类似，

//  这
boolean findA = leftInfo.findA || rightInfo.findA || head == a;
boolean findB = leftInfo.findB || rightInfo.findB || head == b;



if (findA && findB) {
if (leftInfo.findA && leftInfo.findB) {
return new Info(true, true, leftInfo.ancestor);
} else if (rightInfo.findA && rightInfo.findB) {
return new Info(true, true, rightInfo.ancestor);
}
return new Info(true, true, head);
}
return new Info(findA, findB, null);


class Solution {
public static TreeNode lowestCommonAncestor(TreeNode head, TreeNode a, TreeNode b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
// o1和o2都不为null
return p(head, a, b).ancestor;
}

public static Info p(TreeNode head, TreeNode a, TreeNode b) {
if (head == null) {
return new Info(false, false, null);
}
Info leftInfo = p(head.left, a, b);
Info rightInfo = p(head.right, a, b);
boolean findA = leftInfo.findA || rightInfo.findA || head == a;
boolean findB = leftInfo.findB || rightInfo.findB || head == b;
if (findA && findB) {
if (leftInfo.findA && leftInfo.findB) {
return new Info(true, true, leftInfo.ancestor);
} else if (rightInfo.findA && rightInfo.findB) {
return new Info(true, true, rightInfo.ancestor);
}
return new Info(true, true, head);
}
return new Info(findA, findB, null);
}

public static class Info {
public Info(boolean findA, boolean findB, TreeNode ancestor) {
this.findA = findA;
this.findB = findB;
this.ancestor = ancestor;
}

private boolean findA;
private boolean findB;
private TreeNode ancestor;

}
}


## 更多

posted @ 2022-10-06 13:59  Grey Zeng  阅读(240)  评论(0编辑  收藏  举报