Java for LeetCode 236 Lowest Common Ancestor of a Binary Tree

解题思路一:

DFS到每个节点的路径,根据路径算出LCA:

public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
		if (root == p || root == q)
			return root;
		List pList = new ArrayList<TreeNode>(), qList = new ArrayList<TreeNode>();
		getPath(root,p,pList);
		getPath(root,q,qList);
		for(int i=0;i<Math.min(pList.size(), qList.size());i++){
			if(pList.get(i)!=qList.get(i))
				return (TreeNode) pList.get(i-1);
		}
		return (TreeNode) pList.get(Math.min(pList.size(), qList.size())-1);
	}

	private boolean getPath(TreeNode root, TreeNode p, List<TreeNode> path) {
		path.add(root);
		if (root == p)
			return true;
		if (root.left != null) {
			if (getPath(root.left, p, path))
				return true;
			path.remove(path.size() - 1);
		}
		if (root.right != null) {
			if (getPath(root.right, p, path))
				return true;
			path.remove(path.size() - 1);
		}
		return false;
	}
}

解题思路二:

后续遍历+并查集(《数据结构》第11章内容),实现的时间空间,复杂度略高

解题思路三:并查集+Tarjan算法

参考:http://baike.baidu.com/link?url=oJBohljiyLYv4B0lFr5nbXOeYQ6B1PD4jAYAAZ0v2jKWR_ygiKyNFYqfIgWYbST0meiByvGTFNEjftX7vst90q#3_1

转载于:https://www.cnblogs.com/tonyluis/p/4968906.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值