二叉搜尋樹的結構

某朝發表於2024-10-20
#include<iostream>
#include<string>
using namespace std;
typedef struct TreeNode* Tree;
struct TreeNode {
	int v;
	Tree Left, Right;
	int level;
};

Tree NewNode(int V)
{
	Tree T = (Tree)malloc(sizeof(struct TreeNode));
	T->v = V;
	T->Left = T->Right = NULL;
	return T;
}

Tree insert(Tree T, int V)
{
	if (!T)T = NewNode(V);
	else
	{
		if (V > T->v)				
			T->Right = insert(T->Right, V);		
		else 
			T->Left = insert(T->Left, V);
	}
	return T;
}

Tree MakeTree(int n)
{
	Tree T;
	int i, V;
	cin >> V;
	T = NewNode(V);
	for (int i = 1; i < n; i++)
	{
		cin >> V;
		T = insert(T, V);
	}
	return T;
}

Tree findFather(Tree T, int V, Tree parent = nullptr) {
	if (!T) return nullptr;  // 如果樹為空,返回 nullptr
	if (T->v == V) return parent;  // 找到節點 V,返回其父節點

	// 根據值繼續在樹中查詢
	if (V < T->v)
		return findFather(T->Left, V, T);
	else
		return findFather(T->Right, V, T);
}

void judge(Tree T,int m)
{
	for (int i = 1; i <= m; i++)
	{
		string s;
		getchar();
		getline(cin,s);
		if (s.find("root")!=-1) {
			
			cout << "PS:" << T->v << endl;
			int c = s[0]-'0';
			cout << "PS:" << c << endl;
			if (c == T->v) puts("Yes\n");
			else puts("No\n");
		}
		else if(s.find("siblings")) {
			int a = s[0]-'0';
			int b = s[6]-'0';
			if (findFather(T, a) == findFather(T, b)) puts("Yes\n");
			else puts("No\n");
		}
		else if (s.find("level")) {
			int a = s[0] - '0';
			int b = s[6] - '0';
		}

	}
}

int main() {
	int n;
	Tree T;
	cin >> n;
	T=MakeTree(n);
	int m;
	cin >> m;
	judge(T,m);
}

相關文章