二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
递归法:(树的问题大部分可以用递归解决)
/**
* 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){
return null;
}
// p,q中的任一一个为根节点
if (p==root || q == root){
return root;
}
// 单层逻辑
// 检查p,q能否在root.left中找到
TreeNode left =lowestCommonAncestor(root.left, p, q);
// 检查p,q能否在root.right中找到
TreeNode right =lowestCommonAncestor(root.right, p, q);
// 若1满足,2不满足,则最近公共节点为root.left
if(left!=null && right==null){
return left;
}
// 若1不满足,2满足,则最近公共节点为root.right
if(left==null && right!=null){
return right;
}
// 若1满足&2满足,则最近公共节点为root
if(left!=null && right!=null){
return root;
}
return null;
}
}
搜索