1143 Lowest Common Ancestor 解析

开始看到这个题觉得还挺简单的..写个带父节点的BST直接遍历就好了。

结果还是太年轻....会超时...

于是,我们就要在查找的过程中做手脚了..我们同时在树里面查找两个节点,每一轮找完之后,如果发现两个节点一样,我们就记录下来,就是他们的共有父节点。这样就能省下一次查找的时间。

另外这个题的一个坑点:

仔细审题:if the LCA is found and A is the key. But if A is one of U and V, print X is an ancestor of Y.

也就是说,如果这两个点是同一个点。你也是要输出6 is an ancestor of 6.这样的信息。

#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int m, n;
int visitNum = 0;
struct TreeNode {
	int val;
	TreeNode *left = nullptr, *right = nullptr;
	TreeNode() = default;
	TreeNode(int _val) :val(_val) {};
};

typedef TreeNode * Tree;
Tree root;

void Insert(Tree & root, int val);
void Find2(Tree & root, int u, int v);


int main() {
	scanf("%d %d", &m, &n);

	int val;
	for (int i = 0; i < n; i++) {
		scanf("%d", &val);
		Insert(root, val);
	}

	int u, v;
	for (int i = 0; i < m; i++) {
		scanf("%d %d", &u, &v);
		Find2(root, u, v);
	}

	return 0;
}

void Insert(Tree & root, int val) {
	if (!root) {
		root = new TreeNode(val);
		return;
	}

	TreeNode * pre = nullptr;
	TreeNode * now = root;

	while (now){
		pre = now;
		if (val < now->val) {
			now = now->left;
		}
		else {
			now = now->right;
		}
	}

	now = new TreeNode(val);
	if (val < pre->val) {
		pre->left = now;
	}
	else {
		pre->right = now;
	}
}


void Find2(Tree & root, int u, int v) {
	TreeNode * pu = root, *pv = root;
	TreeNode * ans = nullptr;
	bool uisFind = false, visFind = false;
	while (!uisFind && !visFind && pu && pv) {
		if (pu == pv) {
			ans = pu;
		}


		if (u < pu->val) {
			pu = pu->left;
		}
		else if (u > pu->val) {
			pu = pu->right;
		}
		else {
			uisFind = true;
		}

		if (v < pv->val) {
			pv = pv->left;
		}
		else if (v > pv->val) {
			pv = pv->right;
		}
		else {
			visFind = true;
		}

	}


	while (pu && !uisFind) {
		if (u < pu->val) {
			pu = pu->left;
		}
		else if (u > pu->val) {
			pu = pu->right;
		}
		else {
			uisFind = true;
		}
	}

	while (pv && !visFind) {
		if (v < pv->val) {
			pv = pv->left;
		}
		else if (v > pv->val) {
			pv = pv->right;
		}
		else {
			visFind = true;
		}
	}

	if (!uisFind && !visFind) {
		printf("ERROR: %d and %d are not found.\n", u, v);
	}
	else if (!uisFind || !visFind) {
		printf("ERROR: %d is not found.\n", !uisFind ? u : v);
	}
	else {
		if (pu == ans || pv == ans) {
			printf("%d is an ancestor of %d.\n",
				pv == ans ? v : u, pv == ans ? u : v);
		}
		else {
			printf("LCA of %d and %d is %d.\n", u, v, ans->val);
		}
	}
}

 

你可能感兴趣的:(1143 Lowest Common Ancestor 解析)