剑指 Offer 68 - II. 二叉树的最近公共祖先
题目
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
思路
- 如果P和Q都是root的左右节点,那么root就是我们要找的最近公共祖先
- 如果P和Q都是root的左节点,那么返回lowestCommonAncestor(root.left,p,q)
- 如果P和Q都是root的右节点,那么返回lowestCommonAncestor(root.right,p,q)
边界条件讨论:
- 如果root = null 说明找不到,如果root = p或者root = q,返回root
- 如果左子树没找到,递归函数返回null,证明p和q都是在同测,那么就在右子树中查找
- 如果右子树没找到,递归函数返回null,证明p和q都是在同测,那么就在左子树中查找
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q)
{
return root;
}
TreeNode leftNode = lowestCommonAncestor(root.left,p,q);
TreeNode rightNode = lowestCommonAncestor(root.right,p,q);
if(leftNode == null)
{
return rightNode;
}
if(rightNode == null)
{
return leftNode;
}
return root;
}
}