團體天梯 L3-016 二叉搜索樹的結構 (30 分)(測試點分析 C++結構)

L3-016 二叉搜索樹的結構 (30 分)

二叉搜索樹或者是一棵空樹,或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;它的左、右子樹也分別爲二叉搜索樹。(摘自百度百科)

給定一系列互不相等的整數,將它們順次插入一棵初始爲空的二叉搜索樹,然後對結果樹的結構進行描述。你需要能判斷給定的描述是否正確。例如將{ 2 4 1 3 0 }插入後,得到一棵二叉搜索樹,則陳述句如“2是樹的根”、“1和4是兄弟結點”、“3和0在同一層上”(指自頂向下的深度相同)、“2是4的雙親結點”、“3是4的左孩子”都是正確的;而“4是2的左孩子”、“1和3是兄弟結點”都是不正確的。

輸入格式:

輸入在第一行給出一個正整數N(≤100),隨後一行給出N個互不相同的整數,數字間以空格分隔,要求將之順次插入一棵初始爲空的二叉搜索樹。之後給出一個正整數M(≤100),隨後M行,每行給出一句待判斷的陳述句。陳述句有以下6種:

  • A is the root,即"A是樹的根";
  • A and B are siblings,即"AB是兄弟結點";
  • A is the parent of B,即"AB的雙親結點";
  • A is the left child of B,即"AB的左孩子";
  • A is the right child of B,即"AB的右孩子";
  • A and B are on the same level,即"AB在同一層上"。

題目保證所有給定的整數都在整型範圍內。

輸出格式:

對每句陳述,如果正確則輸出Yes,否則輸出No,每句佔一行。

輸入樣例:

5
2 4 1 3 0
8
2 is the root
1 and 4 are siblings
3 and 0 are on the same level
2 is the parent of 4
3 is the left child of 4
1 is the right child of 2
4 and 0 are on the same level
100 is the right child of 3

輸出樣例:

Yes
Yes
Yes
Yes
Yes
No
No
No

注意: 有可能查詢的數結點,並不存在(例如題目樣例,查詢結點8)(測試點2)

完整測試數據分析:來源(https://blog.csdn.net/Dream_Weave/article/details/82744830

#include<iostream>
#include<string>
#include<map>
using namespace std;
struct Node {
	int height;
	int parent = -1;
	int left=-1, right=-1;
};
map<int, Node> tree;
void insert(int head, int tmp,int height) {   //構造搜索樹
	if (head != -1) {
		int r = tmp < head ? tree[head].left : tree[head].right;
		if (r != -1)
			insert(r, tmp,height+1);
		else {
			(tmp < head ? tree[head].left : tree[head].right) = tmp;
			tree[tmp].parent = head;        //記錄父結點
			tree[tmp].height = height;      //存儲結點深度
		}
	}
}
bool judge(int head,int a, int b, string link) {
	if (link == "root")
		return head == a;
	if (tree.find(a) == tree.end() || tree.find(b) == tree.end())  //當搜索的結點不在樹中,返回false
		return false;
	else if (link == "siblings") 
		return tree[a].parent==tree[b].parent;
	else if (link == "parent")
		return tree[a].left == b || tree[a].right == b;
	else if (link == "left")
		return tree[b].left == a;
	else if (link == "right")
		return tree[b].right == a;
	else if (link == "level")
		return tree[a].height == tree[b].height;
}
int main() {
	int n, m, tmp, a=0, b=0, head;
	string link, str;
	cin >> n >> head;
	for (int i = 1; i < n; i++) {
		cin >> tmp;
		insert(head, tmp, 1);
	}
	cin >> m;
	for (int i = 0; i < m; i++) {
		cin >> a >> str;
		if (str == "and") {
			cin >> b >> str >> str;
			if (str == "siblings")
				link = str;
			else 
				cin >> str >> str >> link;	
		}
		else {
			cin >> str >> link;
			if (link == "parent") 
				cin >> str >> b;
			else if(link!="root")
				cin >> str >> str >> b;		
		}
		cout << (judge(head, a, b, link) ? "Yes" : "No") << endl;
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章