题目:输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点
变种一:二叉树是二分查找树,如果根节点比两个节点都小,则访问右子树,都大则访问左子树,否则即为结果
变种二:每个节点有指向父节点的指针,则转变为查找两个单链表的第一个公共节点
变种三:对于普通二叉树,下面给出两种方法
方法一:二叉树的后序遍历,先看节点是否在左子树,再看右子树,然后根据左右子树包含节点的个数,来判断祖先节点的位置
struct BinaryTree
{
int value;
BinaryTree* left;
BinaryTree* right;
BinaryTree(int x):value(x),left(NULL),right(NULL){}
};
BinaryTree* LCA(BinaryTree* root,BinaryTree* node1,BinaryTree* node2)
{
if(root == NULL)return NULL;
if(root == node1 || root == node2)return root;
BinaryTree* left = LCA(root -> left,node1,node2);
BinaryTree* right = LCA(root -> right,node1,node2);
if(left && right)return root;//左右都不为空,则说明左右子树各有一个节点
if(left == NULL)return right;//两个节点都在右子树
return left;//两个节点都在左子树
}
方法二:首先利用递归遍历获得根节点到两个节点的路径,然后判断公共祖先,思想是为了模拟变种二
bool getRoot2NodePath(BinaryTree* root,BinaryTree* node,vector<BinaryTree*>& path)//获得root到node的路径
{
if(root == node)return true;
path.push_back(root);
bool flag = false;
if(root -> left)flag = getRoot2NodePath(root->left,node,path);
if(!flag && root -> right)flag = getRoot2NodePath(root->right,node,path);
if(!flag)path.pop_back();
return flag;
}
BinaryTree* LCA(BinaryTree* root,BinaryTree* node1,BinaryTree* node2)
{
if(root == NULL)return NULL;
vector<BinaryTree*> path1,path2;
getRoot2NodePath(root,node1,path1);
getRoot2NodePath(root,node2,path2);
BinaryTree* p = NULL;
int i = 0;
while(i < path1.size() && i < path2.size())
{
if(path1[i] == path2[i]) p = path1[i++];
else break;
}
return p;
}