最近公共祖先

参考文献1

参考文献2

题目:输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点

变种一:二叉树是二分查找树,如果根节点比两个节点都小,则访问右子树,都大则访问左子树,否则即为结果

变种二:每个节点有指向父节点的指针,则转变为查找两个单链表的第一个公共节点

变种三:对于普通二叉树,下面给出两种方法

方法一:二叉树的后序遍历,先看节点是否在左子树,再看右子树,然后根据左右子树包含节点的个数,来判断祖先节点的位置

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;
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值