树中两个结点的最低公共祖先

60 篇文章 1 订阅

场景一: 二叉搜索树BST

假设是二叉搜索树(二叉搜索树是一个排序的二叉树,左子树的结点小于根结点,右子树的结点大于根结点),故找到一个结点,使其大于左子结点小于右子结点即可。

代码

public static TreeNode getLastCommonNode(TreeNode pRoot, TreeNode pLeft, TreeNode pRight){
	TreeNode treeNode = null;
	if(pRoot == null || pLeft.val > pRight.val){
		return null;
	}
	if(pRoot.val >= pRight.val){
		treeNode = getLastCommonNode(pRoot.left, pLeft, pRight);
	}
	if(pRoot.val <= pLeft.val){
		treeNode = getLastCommonNode(pRoot.right, pLeft, pRight);
	}
	if(pRoot.val >= pLeft.val && pRoot.val <= pRight.val){
		return pRoot;
	}
	return treeNode;
}

场景一: 普通二叉树
假设是普通的二叉树。递归遍历找到所给定的两个结点,然后向上标记,直到有一个结点的左子结点和右子结点都不为空返回

代码

public static BTreeNode getLastCommonNode(BTreeNode pRoot, BTreeNode pLeft, BTreeNode pRight){
	//发现目标节点则通过返回值标记该子树发现了某个目标结点
	if(pRoot == null || pRoot == pLeft || pRoot == pRight){
		return pRoot;
	}
	//查看左子树中是否有目标结点,没有为null
	BTreeNode left = getLastCommonNode(pRoot.left, pLeft, pRight);
	//查看右子树是否有目标节点,没有为null
	BTreeNode right = getLastCommonNode(pRoot.right, pLeft, pRight);
	//都不为空,说明做右子树都有目标结点,则公共祖先就是本身
	if(left != null && right != null){
		return pRoot;
	}
	//如果发现了目标节点,则继续向上标记为该目标节点
	return left == null ? right : right;
}

场景三

假设就是一棵普通的数,子结点没有指向父结点的指针。直接用动态数组保存两个树的路径,然后比较得到第一个公共点。

public static TreeNode getLastCommonParent(TreeNode pRoot, TreeNode p1, TreeNode p2){
	//保存p1的路径
	ArrayList<TreeNode> path1 = new ArrayList<TreeNode>();
	//保存p2的路径
	ArrayList<TreeNode> path2 = new ArrayList<TreeNode>();
	ArrayList<TreeNode> tmpList = new ArrayList<TreeNode>();
	getNodePath(pRoot, p1, tmpList, path1);
	getNodePath(pRoot, p2, tmpList, path2);
	//如果路径不存在,返回空
	if(path1.size() == 0 || path2.size() == 0){
		return null;
	}
	return getLastCommonParent(path1, path2);
}
 
//获取根节点到目标节点的路径
public static void getNodePath(TreeNode pRoot, TreeNode pNode, ArrayList<TreeNode> tmpList, ArrayList<TreeNode> path){
	if(pRoot == pNode || pRoot == null){
		return ;
	}
	tmpList.add(pRoot);
	ArrayList<TreeNode> childs = pRoot.children;
	for(TreeNode node : childs){
		if(node == pNode){
			path.addAll(tmpList);
			break;
		}
		getNodePath(node, pNode, tmpList, path);
	}
	tmpList.remove(tmpList.size()-1); //清空集合
}
	
private static TreeNode getLastCommonParent(ArrayList<TreeNode> path1, ArrayList<TreeNode> path2) {
	TreeNode tmpNode = null;
	for(int i = 0; i < path1.size(); i++){
		if(path1.get(i)!=path2.get(i)){
			break;
		}
	    //循环结束时tmpNode即为最后一个共同结点
		tmpNode = path1.get(i);
	}
	return tmpNode;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值