Lowest Common Ancestor (LCA) of two nodes in graph

1 篇文章 0 订阅

In graph theory and computer science, the lowest common ancestor (LCA) of two nodes v and w in a tree or directed acyclic graph (DAG) is the lowest (i.e. deepest) node that has both v and w as descendants, where we define each node to be a descendant of itself (so if v has a direct connection from ww is the lowest common ancestor).

in this tree, the lowest common ancestor of the nodesx and y is marked in dark green. Other common ancestors are shown in light green.


Problem 1. Find the LCA of two given nodes in Binary Search Tree.

The edge case here is, when root.data = l.data && root.data < r.data, root is the LCA of the two nodes.

public static TreeNode findLCA(TreeNode root, TreeNode a, TreeNode b) {
		if(root==null || a== null || b==null) return root;
		TreeNode l = a.data<b.data ? a:b;
		TreeNode r = a.data>b.data ? a:b;
		if(root.data>=l.data && root.data<=r.data) return root;
		else if(root.data < l.data) return findLCA(root.right,l,r);
		else return findLCA(root.left,l,r);
        
    }
    
	
	public static void main(String[] args) {
		TreeNode root = new TreeNode(10);
		root.right = new TreeNode(11);
		root.left = new TreeNode(9);
		root.left.left = new TreeNode(6);
		root.left.left.left = new TreeNode(3);
		root.left.left.right = new TreeNode(8);
		root.left.left.right.left = new TreeNode(7);
		
		TreeNode a = new TreeNode(3);
		TreeNode b = new TreeNode(7);
		
		System.out.print(findLCA(root,a,b).data);
<span style="white-space:pre">		</span>// 6
	
		
		
	}

Problem 2. Find the LCA of two given nodes in Binary Tree.


public static TreeNode findLCA(TreeNode root, TreeNode a, TreeNode b){
		// if either a or b is the root then root is LCA.
		if(root==null || root.data == a.data || root.data == b.data) return root;
		else{
			//find the LCA from root's left subtree
			TreeNode l = findLCA(root.left,a,b);
			TreeNode r = findLCA(root.right,a,b);
			// if one of a or b is in leftsubtree and other is in right
            // then root is the LCA.
			if(l!=null && r!=null)
				return root;
			// else if l is not null, l is LCA.
			else if(l!=null)
				return l;
			else
				return r;
		}
	}











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值