二叉树两结点的最低共同父结点

题目:二叉树的结点定义如下:

struct TreeNode

{

    int m_nvalue;

    TreeNode* m_pLeft;

    TreeNode* m_pRight;

};

输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点。


struct Node
{
	int val;
	Node *left;
	Node *right;
	Node(int v)
	{
		val = v;
		left = right = NULL;
	}
};

bool getPath(Node *root, Node *target, vector<Node*> &path)
{
	if (root == NULL)
	{
		return false;
	}
	path.push_back(root);
	
	if (root == target)
	{
		return true;
	}

	bool left = getPath(root->left, target, path);
	if (left)
	{
		return true;
	}

	bool right = getPath(root->right, target, path);
	if (right)
	{
		return true;
	}

	path.pop_back();
	return false;
}

Node* getCommonNode(vector<Node*> &path1, vector<Node*> &path2)
{
	if (path1.empty() || path2.empty())
	{
		return NULL;
	}
	int last = min(path1.size()-1, path2.size()-1);
	int i = last;
	int j = last;
	while (path1[i] != path2[j])
	{
		i--;
		j--;
	}
	return path1[i];
}

Node* getParent(Node *root, Node *p, Node *q)
{
	vector<Node*> path1;
	vector<Node*> path2;
	bool a = getPath(root, p, path1);
	if (a)
	{
		bool b = getPath(root, q, path2);
		if (b)
		{
			return getCommonNode(path1, path2);
		}
	}

	return NULL;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值