Lowest Common Ancestor of two nodes in a binary tree

本文深入探讨了在二叉树与二叉搜索树中查找最低公共祖先节点的方法,包括算法实现、复杂度分析及应用案例。通过实例演示了如何在不同类型的树结构中高效定位目标节点,为开发者提供了实用的解决方案。

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

主题:面经

Question:

Find out the Lowest Common Ancestor of two nodes in a Binary Tree.


分析:

LCA的问题,在leetcode的主页上有详解,包括二叉树、二叉搜索树。

如果是二叉搜索树,遍历树节点,如果两个给定节点大于/小于树节点,那么遍历位置右移/左移,直到给定节点等于树节点或者分别在当前树节点的左右两侧,返回当前树节点。复杂度O(log(n))。

如果是二叉树,递归法,从根节点起,寻找左右子树是否存在给定节点,如果返回的左子树右子树都不为空,那么当前的节点就是结果;如果左右有一个为空,那么返回的不为空的子树节点为结果。Base Case是,当前节点为空,返回空;当前节点等于给定节点其中一个,返回当前节点。



代码:

	//binary Tree
	public Node LCA(Node root, Node x1, Node x2){
		if(root == null) return null;
		if(root==x1 || root==x2) return root;
		Node l = LCA(root.left, x1, x2);
		Node r = LCA(root.right, x1, x2);
		if(l!=null && r!=null) return root;
		return l!=null?l:r;
	}
	
	//BST
	public Node getAnces(Node root, Node x1, Node x2){
		if(root==null || x1==null || x2==null) return null;
		if(root.compareTo(x1)>0 && root.compareTo(x2)>0) return getAnces(root.left, x1, x2);
		else if(root.compareTo(x1)<0 && root.compareTo(x2)<0) return getAnces(root.right, x1, x2);
		else return root;
	}

总结:

经典题目。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值