给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
注意事项
假设给出的两个节点都在树中存在
样例
对于下面这棵二叉树
4
/
3 7
/
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
思路:如果两个节点分别在根节点的左子树和右子树,则返回根节点。
如果两个节点都在左子树,则递归处理左子树,如果两个节点都在右子树,则递归处理右子树。
经典笔试题目,要熟练!
/**
* 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 FindNode(TreeNode* root,TreeNode* p){
if(root==NULL||p==NULL){
return false;
}
if(root==p){
return true;
}
bool found=FindNode(root->left,p);
if(!found){
found=FindNode(root->right,p);
}
return found;
}
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
// write your code here
if(root==NULL){
return NULL;
}
if(root==A||root==B){
return root;
}
if(FindNode(root->left,A)){
if(FindNode(root->right,B)){
return root;
}
else{
return lowestCommonAncestor(root->left,A,B);
}
}
else{
if(FindNode(root->left,B)){
return root;
}
else{
return lowestCommonAncestor(root->right,A,B);
}
}
}
};
另一种思路:
先求出从根节点到两个节点的路径;
然后比较两条路径,最后一个相同的节点就是他们在二叉树中的最低公共祖先。
其实将问题转化为求链表第一个相交的节点。