给一棵二叉树和二叉树中的两个节点,找到这两个节点的最近公共祖先LCA。
两个节点的最近公共祖先,是指两个节点的所有父亲节点中(包括这两个节点),离这两个节点最近的公共的节点。
返回 null 如果两个节点在这棵树上不存在最近公共祖先的话。
样例
样例1
输入:
{4, 3, 7, #, #, 5, 6}
3 5
5 6
6 7
5 8
输出:
4
7
7
null
解释:
4
/ \
3 7
. . / \
. . 5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
LCA(5, 8) = null
实现:
public class Solution {
/*
* @param root: The root of the binary tree.
* @param A: A TreeNode
* @param B: A TreeNode
* @return: Return the LCA of the two nodes.
*/
public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
// write your code here
boolean existA = isNodeInTree(root, A);
boolean existB = isNodeInTree(root, B);
if (!existA || !existB) {
return null;
}
return getLowestAncestor(root,A,B);
}
public TreeNode getLowestAncestor(TreeNode root, TreeNode A, TreeNode B){
if (root == null || A == null || B == null) return null;
if (root == A || root == B) return root;
TreeNode left = getLowestAncestor(root.left, A, B);
TreeNode right = getLowestAncestor(root.right, A, B);
if (left != null && right != null) {
return root;
}
if (left != null) {
return left;
}
if (right != null) {
return right;
}
return null;
}
private boolean isNodeInTree(TreeNode root, TreeNode node) {
if (root == null || node == null) return false;
if (root == node) return true;
boolean left = isNodeInTree(root.left, node);
boolean right = isNodeInTree(root.right, node);
return left || right;
}
}