给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
使用于找多个节点的最近公共祖先
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
recurNode(root , p , q);
return tmp;
}
TreeNode tmp = null;
int index = 0;
public int recurNode(TreeNode root , TreeNode p , TreeNode q){
if(root == null){
return 0;
}
int left = recurNode(root.left , p , q);
int right = recurNode(root.right , p , q);
int val = left + right + (root == p || root == q ? 1 : 0);
if(val >= 2 && index == 0){
tmp = root;
index++;
}
return val;
}
另外一种解法:
题解:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/solution/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。