二叉树的公共祖先
二叉树的公共祖先—力扣链接
问题内容:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先
输入输出示例:
1.代码实现
思路分析:
- 如果其中一个是树的根,那么它一定就是公共祖先;
- 接下来无法就是三种情况:全在左子树;全在右子树;一个在左子树,一个在右子树;
/**
* 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;
}
if(root == p || root == q){
return root;
}
TreeNode l = lowestCommonAncestor(root.left,p,q);
TreeNode r = lowestCommonAncestor(root.right,p,q);
if(l != null && r != null){
return root;
}
if(l != null){
return l;
}
if(r != null){
return r;
}
return null;
}
}