《数据结构学习指导与习题解析》-树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wydyd110/article/details/83060162

树的ADT(抽象数据类型)

template <class T>
	
class Tree{
public:
	Tree();                               		// 拷贝构造函数
	virtual ~Tree();                      		// 析构函数
	TreeNode<T>* getRoot();               		// 返回树中的根结点
	void CreateRoot(const T& rootValue);  		// 创造值为rootValue的根结点
	bool isEmpty();                       		// 判断是否为空树
	TreeNode<T>* Parent(TreeNode<T> *current); 	// 返回父结点
	TreeNode<T>* PrevSibling(TreeNode<T> *current); // 返回前一个兄弟
	void DeleteSubTree(TreeNode<T> *subroot); 	// 删除以subroot子树
	void RootFirstTraverse(TreeNode<T> *root); 	// 先根深度优先遍历树
	void RootLastTraverse(TreeNode<T> *root); 	// 后根深度优先遍历树
	void WidthTraverse(TreeNode<T> *root); 		// 广度优先遍历树
}; 

树结点的ADT

template <class T>
	
class TreeNode{
public:
	TreeNode(const T& value);             // 拷贝构造函数.参数为结点的值
	virtual ~TreeNode() {};               // 析构函数
	bool isLeaf();                        //判断当前结点是否为叶结点
	T Value();                            //返回结点的值
	TreeNode<T> *LeftMostChild();         //返回第一个左孩子
	TreeNode<T> *RightSibling();          //返回右兄弟
	void setValue(const T &value);        // 设置当前结点的值
	void setChild(TreeNode<T> *pointer);  // 设置左孩子  
	void setSibling(TreeNode<T> *pointer);// 设置右兄弟
	void InsertFirst(TreeNode<T> *node);  // 以第一个左孩子身份插入结点
	void InsertNext(TreeNode<T> *node);   // 以右兄弟的身份插入结点
}; 

1

解析:

根结点:A

树叶:E F H I J

树转换成二叉树:

参考:数据结构树之切腹攻略

2

对于3个结点A,B,C,有多少个不同的有向树?有多少个不同的有序树?把它们画出来。

解析:

3

编写一个算法判断两棵树是否相同。尽可能提高算法效率,分析算法的运行时间代价。

解析:

要求树的结构相同且对应结点的值相等

(1)采用递归法

(2)采用非递归法,以某种次序同时遍历二叉树,同时比较结点

递归法1

bool isEqual(TreeNode<T> *root1, TreeNode<T> *root2)
{
	while(root1 != NULL && root2 != NULL)
	{
		//比较对应的结点,若不相等则直接返回
		if(root1 -> value() != root2 -> value()) return false;
		//若最左子树不相等则返回false
		if(false == isEqual(root1 -> LeftMostChild()),root2 -> LeftMostChild()) return false;
		//比较下一棵子树
		root1 = root1 -> RightSibling(); //右兄弟
		root2 = root2 -> RightSibling();//右兄弟
	}
	//若此时root1 和 root2都是NULL,返回true
	//包括一开始就为空的情况,也包括执行完while循环后都不返回false的情况,即两个树都遍历完的情况
	if(root1 == NULL && root2 == NULL) return true;
	return false;
}

猜你喜欢

转载自blog.csdn.net/wydyd110/article/details/83060162