版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/85198132
给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
样例
对于下面这棵二叉树
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
注意事项
假设给出的两个节点都在树中存在
解题思路:
分治法。
假设左子树找到了LCA,右子树找到了LCA,说明root是LCA
假设左子树找到了LCA,右子树没找到,说明左子树LCA就是整棵树的LCA,同理右子树。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: The root of the binary search tree.
* @param A: A TreeNode in a Binary.
* @param B: A TreeNode in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
//如果找到了就返回这个LCA
//如果只找到了A,就返回A
//如果只找到了B,就返回B
//如果都没有返回null
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
// write your code here
if(root == null || root == A || root == B)
return root;
TreeNode rightNode = lowestCommonAncestor(root.right, A, B);
TreeNode leftNode = lowestCommonAncestor(root.left, A, B);
if(rightNode != null && leftNode != null)
return root;
if(rightNode != null)
return rightNode;
if(leftNode != null)
return leftNode;
return null;
}
}