【东华大学oj】二叉树:距离最近的共同祖先

二叉树:距离最近的共同祖先

时间限制: 1s

类别: DS:树->中等

问题描述

目的:使用C++模板设计二叉树的抽象数据类型(ADT)。并在此基础上,使用二叉树ADT的基本操作,设计并实现简单应用的算法设计。

内容:(1)请参照链表的ADT模板,设计二叉树的抽象数据类型。(由于该环境目前仅支持单文件的编译,故将所有内容都集中在一个源文件内。在实际的设计中,推荐将抽象类及对应的派生类分别放在单独的头文件中。参考教材、课件,以及网盘中的链表ADT原型文件,自行设计二叉树的ADT。)

注意:二叉树ADT的基本操作的算法设计很多要用到递归的程序设计方法。

(2)ADT的简单应用:使用该ADT设计并实现若干应用二叉树的算法设计。

应用:要求设计一个算法,查找距离二叉树中2个结点最近的共同祖先。二叉树的存储结构的建立参见二叉树应用1。

注意:x、y都是属于该二叉树的结点。

参考函数原型:

//查找距离二叉树中2个结点最近的共同祖先 (用户函数)

template<class ElemType>

BinaryTreeNode<ElemType> * FindNearAncient( BinaryTree<ElemType> &T, ElemType &x, ElemType &y );     

辅助函数:

//查找从根结点到元素值为x的结点的路径 (成员函数,参见基本操作18)

template<class ElemType> //Q为存放路径的顺序队列

void BinaryTree<ElemType>::FindPath( ElemType &x, SqQueue<BinaryTreeNode<ElemType> *> &Q );

输入说明

第一行:表示无孩子或指针为空的特殊分隔符

第二行:二叉树的先序序列(结点元素之间以空格分隔)

第三行:元素值x

第四行:元素值y

输出说明

第一行:元素值(共同祖先)

如x、y中有根结点,则输出NULL


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <sstream>
#include <stack>
#include <map>
#include <ctime>
#include <array>
#include <set>
using namespace std;
vector<string> departString_string(string data)
{
	vector<int> back_part;//output type
	int i, j;
	vector<string> part;
	string A_part;
	stringstream room;
	room.str(data);
	while (room >> A_part)
		part.push_back(A_part);
	return part;
}

template<class ElemType>
struct tree_point {
	ElemType data;//数据
	struct tree_point* l_child, * r_child;//左、右孩子指针
};
template<class ElemType>
class BinaryTree {
private:
	vector<tree_point<ElemType>*> outlist;
	tree_point<ElemType>* root;   // 头指针
public:
	BinaryTree() :root(NULL)
	{
		//无参数的构造函数
	}
	~BinaryTree()
	{
		//析构函数
	}
	void BinaryTree_fron(vector<ElemType> lis, ElemType nut)
	{
		stack<tree_point<ElemType>*> s;
		tree_point<ElemType>* p_Parent = NULL, * p_Child = NULL;
		int i = 0;
		int flag = 0;//控制左右
		p_Parent = new tree_point<ElemType>;
		p_Parent->data = lis[i];
		p_Parent->l_child = p_Parent->r_child = NULL;
		s.push(p_Parent);
		root = p_Parent;
		i = 1;
		flag = 0;
		while (!s.empty())
		{
			if (lis[i] != nut)
			{
				p_Parent = new tree_point<ElemType>;
				p_Parent->data = lis[i];
				p_Parent->l_child = p_Parent->r_child = NULL;
				if (flag == 0)
				{
					p_Child = s.top();
					p_Child->l_child = p_Parent;
				}
				else if (flag == 1)
				{
					p_Child = s.top();
					s.pop();
					p_Child->r_child = p_Parent;
				}
				s.push(p_Parent);
				flag = 0;
			}
			else
			{
				if (flag == 0)
					flag = 1;
				else if (flag == 1)
					s.pop();
			}
			i++;
		}
	}
	tree_point<ElemType>* get_root()
	{
		return root;
	}
	void s_qianxu(void)
	{
		outlist.clear();
		if (root == NULL)
			return;
		tree_point<ElemType>* p = root;
		stack<tree_point<ElemType>*> s;
		while (!s.empty() || p)
		{
			while (p)
			{
				outlist.push_back(p);
				s.push(p);
				p = p->l_child;
			}
			if (!s.empty())
			{
				p = s.top();
				s.pop();
				p = p->r_child;
			}
		}
		return;
	}
	void s_zhongxu(void)
	{
		outlist.clear();
		if (root == NULL)
			return;
		tree_point<ElemType>* p = root;
		stack<tree_point<ElemType>*> s;
		while (!s.empty() || p)
		{
			if (p)
			{
				s.push(p);
				p = p->l_child;
			}
			else
			{
				p = s.top();
				s.pop();
				outlist.push_back(p);
				p = p->r_child;
			}
		}
		return;
	}
	void s_houxu(void)
	{
		if (root == NULL)
			return;
		stack<tree_point<ElemType>*> s;
		//pCur:当前访问节点,pLastVisit:上次访问节点
		tree_point<ElemType>* pCur, * pLastVisit;
		pCur = root;
		pLastVisit = NULL;
		while (pCur)
		{
			s.push(pCur);
			pCur = pCur->l_child;
		}
		while (!s.empty())
		{
			pCur = s.top();
			s.pop();
			if (pCur->r_child == NULL || pCur->r_child == pLastVisit)
			{
				outlist.push_back(pCur);
				pLastVisit = pCur;
			}
			else
			{
				s.push(pCur);
				pCur = pCur->r_child;
				while (pCur)
				{
					s.push(pCur);
					pCur = pCur->l_child;
				}
			}
		}
		return;
	}
	void qianxu(tree_point<ElemType>* t)
	{
		outlist.push_back(t);
		if (t->l_child != NULL)
			qianxu(t->l_child);
		if (t->r_child != NULL)
			qianxu(t->r_child);
		return;
	}
	void zhongxu(tree_point<ElemType>* t)
	{
		if (t->l_child != NULL)
			zhongxu(t->l_child);
		outlist.push_back(t);
		if (t->r_child != NULL)
			zhongxu(t->r_child);
		return;
	}
	int two_n(int twoNum)
	{
		int ans = 1;
		while (twoNum--)
			ans *= 2;
		return ans;
	}
	void houxu(tree_point<ElemType>* t)
	{
		if (t->l_child != NULL)
			houxu(t->l_child);
		if (t->r_child != NULL)
			houxu(t->r_child);
		outlist.push_back(t);
		return;
	}
	int c_t = 0;
	int full_floorTree = 0;
	void cengxu(tree_point<ElemType>* t)
	{
		vector<tree_point<ElemType>* > q;
		q.push_back(t);
		int last = 1, cur = 0,ceng_num;
		while (cur < q.size())
		{
			ceng_num = 0;
			last = q.size();
			while (cur < last)
			{
				outlist.push_back(q[cur]);
				if (q[cur]->l_child)
					q.push_back(q[cur]->l_child);
				if (q[cur]->r_child)
					q.push_back(q[cur]->r_child);
				++cur;
				ceng_num++;
			}
			c_t++;
			if (ceng_num != two_n(c_t-1))
			{
				full_floorTree ++;
			}

		}
	}
	bool floorCheck_full()
	{
		if (!root)
			return 0;
		queue<tree_point<ElemType>* > Q;
		tree_point<ElemType>* p;
		p = root;
		Q.push(p);
		while (!Q.empty())
		{
			p = Q.front();
			Q.pop();
			if (p==NULL)
				break;
			Q.push(p->l_child);
			Q.push(p->r_child);
		}
		while (!Q.empty())
		{
			p = Q.front();
			Q.pop();
			if (p)
				return false;
		}
		return true;
	}
	void out_lis()
{
    for (int i = 0; i < outlist.size(); i++)
    {
        printf("%s", outlist[i]->data.c_str());
        if (i != outlist.size() - 1)
            printf(",");
        else
            printf("\n");
    }
    outlist.clear();
}

	int cnt = 0, p_cnt = 0;
	void t_cnt(tree_point<ElemType>* t)
	{
		p_cnt++;
		if (t->l_child != NULL && t->r_child != NULL)
			cnt++;
		if (t->l_child != NULL)
			t_cnt(t->l_child);
		if (t->r_child != NULL)
			t_cnt(t->r_child);
	}
	int cengshu()
	{
		c_t = 0;
		cengxu(root);
		outlist.clear();
		return c_t;
	}
	int P_cengshu(tree_point<ElemType>* t)
	{
		c_t = 0;
		cengxu(t);
		outlist.clear();
		return c_t;
	}
	int twocnt()
	{
		cnt = 0;
		t_cnt(root);
		return cnt;
	}
	int P_twocnt(tree_point<ElemType>* t)
	{
		cnt = 0;
		t_cnt(t);
		return cnt;
	}
	int pointcnt()
	{
		p_cnt = 0;
		t_cnt(root);
		return p_cnt;
	}
	tree_point<ElemType>* father_p;
	void find_fatherNow(tree_point<ElemType>* t, ElemType ss)
	{
		if (t->l_child != NULL)
			if (t->l_child->data == ss)
			{
				father_p = t;
				return;
			}
		if (t->r_child != NULL)
			if (t->r_child->data == ss)
			{
				father_p = t;
				return;
			}
		if (t->l_child != NULL)
			find_fatherNow(t->l_child, ss);
		if (t->r_child != NULL)
			find_fatherNow(t->r_child, ss);
		return;
	}
	tree_point<ElemType>* find_father(tree_point<ElemType>* t, ElemType ss)
	{
		father_p = NULL;
		find_fatherNow(t, ss);
		return father_p;
	}
	tree_point<ElemType>* nas_p;
	void find_selfNOW(tree_point<ElemType>* t, ElemType ss)
	{
		if (t->data == ss)
			nas_p = t;
		if (t->l_child != NULL)
			find_selfNOW(t->l_child, ss);
		if (t->r_child != NULL)
			find_selfNOW(t->r_child, ss);
		return;
	}
	tree_point<ElemType>* find_self(tree_point<ElemType>* t, ElemType ss)
	{
		nas_p = NULL;
		find_selfNOW(t, ss);
		return nas_p;
	}
	void fast_delChild(tree_point<ElemType>* t, bool flag)
	{
		if (flag == 0)
			t->l_child = NULL;
		else
			t->r_child = NULL;
		return;
	}
	void slow_delChild(tree_point<ElemType>* t, bool flag)
	{
		if (flag == 0)
			t->l_child = NULL;
		else
			t->r_child = NULL;
		return;
	}
	bool is_same = 1;
	bool check_same(tree_point<ElemType>* t1, tree_point<ElemType>* t2)
	{
		if (((t1->l_child != NULL && t2->l_child != NULL) || (t1->l_child == NULL && t2->l_child == NULL))
			&& ((t1->r_child != NULL && t2->r_child != NULL) || (t1->r_child == NULL && t2->r_child == NULL))
			&& t1->data == t2->data)
		{
			if (t1->l_child != NULL)
				check_same(t1->l_child,t2->l_child);
			if (t1->r_child != NULL)
				check_same(t1->r_child, t2->r_child);
		}
		else
		{
			is_same = 0;
			return 0;
		}

	}
	bool operator==(BinaryTree B2)
	{
		is_same = 1;
		check_same(root, B2.get_root());
		return is_same;
	}
	vector<ElemType> path_note;
	void find_path_DFS(tree_point<ElemType>* t, ElemType num)//递归寻找元素节点
	{
		path_note.push_back(t->data);
		if (t->data == num)
		{
			int i;
			for (i = 0; i < path_note.size()-1; i++)
				     printf("%s->", path_note[i].c_str());
        printf("%s\n", path_note[path_note.size()-1].c_str());
		}
		if (t->l_child != NULL)
			find_path_DFS(t->l_child, num);
		if (t->r_child != NULL)
			find_path_DFS(t->r_child, num);
		path_note.erase(path_note.end() - 1);
	}
	void find_path(ElemType elemt)
	{
		find_path_DFS(root, elemt);
		return;
	}
	tree_point<ElemType>* find_sameFather_DFS(tree_point<ElemType>* t, tree_point<ElemType>*p, tree_point<ElemType>*q)
	{
		if (t == NULL)
			return NULL; // 如果树为空,直接返回null
		if (t == p || t == q)
			return t; // 如果 p和q中有等于 root的,那么它们的最近公共祖先即为root
		// 左子树和右子树
		tree_point<ElemType>* N_left = find_sameFather_DFS(t->l_child, p, q);
		// 遍历左子树,找到了p或q,则先返回
		tree_point<ElemType>* N_right = find_sameFather_DFS(t->r_child, p, q);
		// 遍历右子树,找到了p或q,则先返回
		if (N_left == NULL)
			return N_right;
		// p和 q都找不到,则 p和 q一定都在右子树中,先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
		else if (N_right == NULL)
			return N_left;
		// 如果 l不为空,在左子树中有找到节点(p或q),这时候要再判断一下右子树中的情况,如果在右子树中,p和q都找不到,则 p和q一定都在左子树中
		else return t;
		//当 l和 r均不为空时,说明 p、q节点分别在 root异侧, 最近公共祖先即为 root
	}
	tree_point<ElemType>* find_sameFather(ElemType pas_a, ElemType pas_b)
	{
		tree_point<string>* ans, * tp1, * tp2;
		tp1 = find_self(root, pas_a);
		tp2 = find_self(root, pas_b);
		if (tp1 == root || tp2 == root)
			return NULL;
		ans = find_sameFather_DFS(root, tp1, tp2);
		if (ans == tp1)
		{
			ans = find_father(root, ans->data);
		}
		if (ans == tp2)
		{
			ans = find_father(root, ans->data);
		}
		return ans;
	}
};

int main()
{
	string s, ins, ins1, nulls;
	vector<string> part_in, part_in1;
	BinaryTree<string> a;
	/*BinaryTree<string> b;*/
	cin >> nulls;
	cin.get();
	getline(cin, ins);
	part_in = departString_string(ins);
	a.BinaryTree_fron(part_in, nulls);
	string pas_a,pas_b;
	cin >> pas_a >> pas_b;
	auto ans = a.find_sameFather(pas_a, pas_b);
	 if (ans == NULL)
        printf("NULL\n");
    else
        printf("%s\n", ans->data.c_str());
	return 0;
}

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ixll625

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值