Lowest Commen Ancensor

查找两个node的最近公共祖先。

参考一个最近公共祖先例子:http://blog.csdn.net/chencheng126/article/details/40450281

思路:

1,如果两个node在root的两边,则最近公共祖先就是root

2,如果两个node在root的左边,则把root->left作为root,递归

3,如果两个node在root的右边,则吧root->right作为root,递归

定义一个递归函数covers,来判断该节点是否能够到达原始节点。然后就可以很方便实现上面三种情况。


对于二叉查找树,如果两个节点的值都比root小,则在root左边;如果都比root大,则在root右边;如果都不是,则这个root就是LCA。

#include <iostream>
using namespace std;

struct TreeNode
{
	int data;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x):data(x),left(NULL),right(NULL) {}
};

//在二叉树中找最近公共祖先
class solution
{
public:
	//check the node is in the tree
	bool covers(TreeNode *root,TreeNode *n)
	{
		if(root == NULL) return false;
		if(root == n) return true;
		return covers(root->left,n) || covers(root->right,n);
	}

	TreeNode *commonAncestor(TreeNode *root,TreeNode *p,TreeNode *q)
	{
		if(covers(root->left,p) && covers(root->left,q))
			return commonAncestor(root->left,p,q);
		if(covers(root->right,p) && covers(root->right,q))
			return commonAncestor(root->right,p,q);
		return root;
	}
};

//如果是二叉查找树
class solution2
{
public:
	TreeNode *LCA(TreeNode *root,TreeNode *p,TreeNode *q)
	{
		if(root == NULL || p == NULL || q == NULL) return NULL;
		if(max(p->data,q->data) < root->data)
			return LCA(root->left,p,q);
		else if(min(p->data,q->data) > root->data)
			return LCA(root->right,p,q);
		else
			return root;
	}
};


你可能感兴趣的:(Lowest Commen Ancensor)