题目描述:
标签:树
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
代码:
思路分析:
1、递归结束条件,找到p,q节点即root=p或root=q时或root为空时,返回root
2、左递归,left=递归(root.left,p,q)
3、右递归,right=递归(root.right,p,q)
4、如果left和right都不为空,则返回root
5、如果left为空right不为空,返回right
如果left不为空right为空,返回left
如果两者都为空,返回null
/**
* 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 == p || root == q || root == null){
return root;
}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left != null && right != null){
return root;
}
if(left == null && right != null){
return right;
}else if(left != null && right == null){
return left;
}else{
return null;
}
}
}