给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
本题我的思路是简单的定义一个递归搜索函数,在树中找到该节点就返回true,否则false。主函数中先对左右子树进行搜索,若左右子树有符合条件的公共祖先则返回,没有再判断根。
if(root == null){return null;}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left!=null){
return left;
}
if(right != null){
return right;
}
if(find(root,p)==true&&find(root,q)==true){
return root;
}
return null;
}
boolean find(TreeNode root,TreeNode p){
if(root==null){return false;}
if(root.val==p.val){return true;}
return find(root.left,p)||find(root.right,p)||false;
}