求两个结点的公共祖先

本文介绍了两种在二叉树中查找两个指定节点的最近公共祖先的方法:一种是使用迭代方式,通过构建路径来确定公共祖先;另一种是采用递归方式,直接在树中搜索节点并返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
	 *  将路径上的节点添加到队列中去
	 */
	public static boolean LCAPath(Node root,int x,ArrayList<Long> path){
		if(root==null)
			return false;
		path.add(root.element);
		if(root.element!=x&&!LCAPath(root.leftChild, x, path)&&!LCAPath(root.rightChild, x, path)){
			path.remove(root.element);
			return false;
		}
		return true;
	}

上面的函数将从根结点开始的路径放入list中。

/*
	 * 二叉树求公共祖先(迭代版)
	 */
	public static Long findLCA(Node root,int x,int y){
		ArrayList<Long> path1 =new ArrayList();
		ArrayList<Long> path2 =new ArrayList();
		//获取到两个结点的路径
		LCAPath(root,x, path1);
		LCAPath(root,y, path2);
		//遍历两条路径
		Iterator<Long> ite1=path1.iterator();
		Iterator<Long> ite2=path2.iterator();
		//当前指针记录相同的结点
		Long currentNum=(long) 0;
		while(ite1.hasNext()&&ite2.hasNext()){
			long i=ite1.next();
			long j=ite2.next();
			if(i==j){
				currentNum=i;
			}else{
				break;
			}
		}
		return currentNum;
	}

下面是递归版,但是效率要低一些,

/*
	 * 二叉树中求两结点的最近祖先(递归版)
	 * 
	 */
	public static Node findBtreeLca(Node root,int x,int y){
		if(root==null)
			return null;
		if(root.element==x||root.element==y)
			return root;
		Node left=findBtreeLca(root.leftChild, x, y);
		Node right=findBtreeLca(root.rightChild, x, y);
		if(left==null)
			return right;
		else if(right==null)
			return left;
		return root;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值