给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
注意事项
假设给出的两个节点都在树中存在
样例
对于下面这棵二叉树
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
思路:递归查找。先判断A和B是否在同一侧子树,不是就返回根结点即父结点,是则继续查找父结点。
都在右子树或都在左子树,就继续递归寻找公共父节点,不在同一子树就返回当前根结点即父结点。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
bool postOrder(TreeNode *root, TreeNode *A){
if (root == NULL) return false;
if (root == A) {
return true;
}
//在右子树或在左子树都返回true
return (postOrder(root->left,A)|| postOrder(root->right,A));
}
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
if (root == NULL ) return NULL;
bool ra = postOrder(root->right,A);//判断A是否在右子树
bool rb = postOrder(root->right,B);//判断B是否在右子树
bool la = postOrder(root->left,A); //判断A是否在左子树
bool lb = postOrder(root->left,B); //判断B是否在左子树
if (ra && rb) { //都在右子树,继续寻找公共父节点
return lowestCommonAncestor (root->right,A,B);
} else if (la && lb) { //都在左子树,继续寻找公共父节点
return lowestCommonAncestor(root->left,A,B);
} else { //不在同一子树,最后的公共父节点
return root;
}
}
};