Lowest Common Ancestor

1. 如果只有一次查询,参考 http://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/的解法。

代码如下:

TreeNode* LCAcommon(TreeNode *root, TreeNode *n1, TreeNode* n2)
{
	if(root == NULL) return NULL;
	if(root == n1 || root == n2) return root;

	TreeNode *lca_left  = LCAcommon(root->left, n1, n2);
	TreeNode *lca_right = LCAcommon(root->right, n1, n2);

	if(lca_left && lca_right) return root;

	if(lca_left)
		return lca_left;
	else
		return lca_right;
}


如果不能确定要查询的两个点是否存在,可以使用以下的代码进行判断,如果有一个节点不存在,则需要返回null。

// This function returns pointer to LCA of two given values n1 and n2.
// v1 is set as true by this function if n1 is found
// v2 is set as true by this function if n2 is found
struct Node *findLCAUtil(struct Node* root, int n1, int n2, bool &v1, bool &v2)
{
    // Base case
    if (root == NULL) return NULL;
 
    // If either n1 or n2 matches with root's key, report the presence
    // by setting v1 or v2 as true and return root (Note that if a key
    // is ancestor of other, then the ancestor key becomes LCA)
    if (root->key == n1)
    {
        v1 = true;
        return root;
    }
    if (root->key == n2)
    {
        v2 = true;
        return root;
    }
 
    // Look for keys in left and right subtrees
    Node *left_lca  = findLCAUtil(root->left, n1, n2, v1, v2);
    Node *right_lca = findLCAUtil(root->right, n1, n2, v1, v2);
 
    // If both of the above calls return Non-NULL, then one key
    // is present in once subtree and other is present in other,
    // So this node is the LCA
    if (left_lca && right_lca)  return root;
 
    // Otherwise check if left subtree or right subtree is LCA
    return (left_lca != NULL)? left_lca: right_lca;
}
 
// Returns true if key k is present in tree rooted with root
bool find(Node *root, int k)
{
    // Base Case
    if (root == NULL)
        return false;
 
    // If key is present at root, or in left subtree or right subtree,
    // return true;
    if (root->key == k || find(root->left, k) ||  find(root->right, k))
        return true;
 
    // Else return false
    return false;
}
 
// This function returns LCA of n1 and n2 only if both n1 and n2 are present
// in tree, otherwise returns NULL;
Node *findLCA(Node *root, int n1, int n2)
{
    // Initialize n1 and n2 as not visited
    bool v1 = false, v2 = false;
 
    // Find lca of n1 and n2 using the technique discussed above
    Node *lca = findLCAUtil(root, n1, n2, v1, v2);
 
    // Return LCA only if both n1 and n2 are present in tree
    if (v1 && v2 || v1 && find(lca, n2) || v2 && find(lca, n1))
        return lca;
 
    // Else return NULL
    return NULL;
}


2. 如果有多次查询,可以使用Trajan算法,使用Union Set 进行预处理。

参考:  http://en.wikipedia.org/wiki/Tarjan%27s_off-line_lowest_common_ancestors_algorithm

http://scturtle.is-programmer.com/posts/30055.html

算法代码:

<pre name="code" class="cpp">#include <iostream>
#include <map>
#include <vector>
using namespace std;

struct TreeNode
{
	TreeNode *left;
	TreeNode *right;
	int val;
	TreeNode(int _val): val(_val) {}
};

//for union set
map<TreeNode*, TreeNode*> parent;
map<TreeNode*, int> rank;

//for LCA algorithm
map<TreeNode*, TreeNode*> ancestor;
map<TreeNode*, bool> visited;

void MakeSet(TreeNode* root)
{
	parent[root] = root;
	rank[root] = 0;
}

TreeNode* FindSet(TreeNode *node)
{
	if(parent[node] == node)
		return node;
	parent[node] = FindSet(parent[node]);
	return parent[node];
}

void Union(TreeNode *node1, TreeNode *node2)
{
	TreeNode* root1 = FindSet(node1);
	TreeNode* root2 = FindSet(node2);
	if(root1 == root2) return;

	int rank1 = rank[root1];
	int rank2 = rank[root2];
	if(rank1 > rank2)
		parent[root2] = root1;
	else
	{
		parent[root1] = root2;
		if(rank1 == rank2)
			rank[root2]++;
	}
}

void LCATrajan(TreeNode *root, vector<pair<TreeNode*, TreeNode*> > &query)
{
	MakeSet(root);
	ancestor[FindSet(root)] = root;
	if(root->left)
	{
		LCATrajan(root->left, query);
		Union(root->left, root);
		ancestor[FindSet(root->left)] = root;
	}
	if(root->right)
	{
		LCATrajan(root->right, query);
		Union(root->right, root);
		ancestor[FindSet(root->right)] = root;
	}
	visited[root] = true;
	for(int i=0; i<query.size(); i++)
	{
		TreeNode *first = query[i].first;
		TreeNode *second = query[i].second;
		if(first == root && visited[second] == true)
		{
			cout << (first->val) << " " << (second->val)
					<< " " << ancestor[FindSet(second)]->val << endl;
		}
		else if(second == root && visited[first] == true)
		{
			cout << (first->val) << " " << (second->val)
					<< " " << ancestor[FindSet(first)]->val << endl;
		}
	}
}

int main()
{
	// Let us create binary tree given in the above example
	TreeNode * root = new TreeNode(1);

	TreeNode *t2 = new TreeNode(2);
	TreeNode *t3 = new TreeNode(3);
	TreeNode *t4 = new TreeNode(4);
	TreeNode *t5 = new TreeNode(5);
	TreeNode *t6 = new TreeNode(6);
	TreeNode *t7 = new TreeNode(7);

	root->left = t2;
	root->right = t3;
	root->left->left = t4;
	root->left->right = t5;
	root->right->left = t6;
	root->right->right = t7;

	vector<pair<TreeNode*, TreeNode*> > query;
	query.push_back(make_pair(t4, t5));
	query.push_back(make_pair(t4, t6));
	query.push_back(make_pair(t4, t3));
	query.push_back(make_pair(t2, t4));

	LCATrajan(root, query);

	return 0;
}

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C#中二叉树的lowest common ancestor的源代码: ```csharp using System; public class Node { public int value; public Node left; public Node right; public Node(int value) { this.value = value; this.left = null; this.right = null; } } public class BinaryTree { public Node root; public BinaryTree() { this.root = null; } public Node LowestCommonAncestor(Node node, int value1, int value2) { if (node == null) { return null; } if (node.value == value1 || node.value == value2) { return node; } Node left = LowestCommonAncestor(node.left, value1, value2); Node right = LowestCommonAncestor(node.right, value1, value2); if (left != null && right != null) { return node; } return (left != null) ? left : right; } } public class Program { public static void Main() { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); Node lca = tree.LowestCommonAncestor(tree.root, 4, 5); Console.WriteLine("Lowest Common Ancestor of 4 and 5: " + lca.value); lca = tree.LowestCommonAncestor(tree.root, 4, 6); Console.WriteLine("Lowest Common Ancestor of 4 and 6: " + lca.value); lca = tree.LowestCommonAncestor(tree.root, 3, 4); Console.WriteLine("Lowest Common Ancestor of 3 and 4: " + lca.value); lca = tree.LowestCommonAncestor(tree.root, 2, 4); Console.WriteLine("Lowest Common Ancestor of 2 and 4: " + lca.value); } } ``` 在上面的代码中,我们定义了一个Node类和一个BinaryTree类。我们使用BinaryTree类来创建二叉树,并实现了一个LowestCommonAncestor方法来计算二叉树中给定两个节点的最近公共祖先。 在LowestCommonAncestor方法中,我们首先检查给定节点是否为null或与给定值之一匹配。如果是,则返回该节点。否则,我们递归地在左子树和右子树上调用LowestCommonAncestor方法,并检查它们的返回值。如果左子树和右子树的返回值都不为null,则当前节点是它们的最近公共祖先。否则,我们返回非null的那个子树的返回值。 在Main方法中,我们创建了一个二叉树,并测试了LowestCommonAncestor方法的几个不同输入。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值