C++算法入门练习——相同的二叉查找树

将第一组n​个互不相同的正整数先后插入到一棵空的二叉查找树中,得到二叉查找树T1​;再将第二组n个互不相同的正整数先后插入到一棵空的二叉查找树中,得到二叉查找树T2​。判断T1​和T2​​是否是同一棵二叉查找树。

C++算法入门练习——相同的二叉查找树_第1张图片

C++算法入门练习——相同的二叉查找树_第2张图片二叉查找(搜索)树定义:

 ①要么二叉查找树是一颗空树。

②要么二叉查找树由根节点、左子树、右子树构成,其中左子树和右子树都是二叉查找树,且左子树上所有结点的数据域都小于或等于根结点的数据域,右子树上所有的结点的数据域均大于根节点的数据域。

由定义可以发现这么一个二叉查找树的性质:

二叉查找树如果中序遍历(左儿子,根结点,右儿子)得到的必定是一个由小到大的有序序列。

而正是因为这么一个性质,才被称为查找树。

回到本题解题思路:

根据给定的两组数进行建立二叉查找树,然后进行先序遍历得到序列,若二者的先序遍历序列相等,则说明为同一棵树。

完整代码如下:

#include 
#include 
using namespace std;

struct node{
	int data;
	int lchild;
	int rchild;
}nodes[51];

int nodecount = 0;
vector tree1,tree2;


void PreOrderTraverse(int root,vector& tree){//注意要用引用,这样才改变内容,不然只是浅拷贝。
	if(root == -1){
		return;
	}
	tree.push_back(nodes[root].data);
	PreOrderTraverse(nodes[root].lchild,tree);
	PreOrderTraverse(nodes[root].rchild,tree);
}

int newNode(int data){
	nodes[nodecount].data = data;
	nodes[nodecount].lchild = -1;
	nodes[nodecount].rchild = -1;
	return nodecount++;
}

int insert(int root,int data){
	if(root == -1){//若根结点为-1,则说明找到了插入的位置。
		return newNode(data);
	}
	if(data>n;
	int data[n];
	for(int i=0;i>data[i];
	}
	int root = buildtree(n,data);
	PreOrderTraverse(root,tree1);
	for(int i=0;i>data[i];
	}
	root = buildtree(n,data);
	PreOrderTraverse(root,tree2);
	if(tree1==tree2){
		cout<<"Yes"<

你可能感兴趣的:(算法,c++,数据结构)