创建二叉树(递归+先序遍历)

创建二叉树(递归+先序遍历)

(1) 自输入数据元素,形参为引用类型或二级指针

class treeNode
{
public:
	int value;
	treeNode *left;
	treeNode *right;
};

//  递归+先序遍历创建二叉树
void createBinaryTree(treeNode *&root)   //  形参必须声明为引用类型或二级指针
{
	int num;
	cin >> num;
	if (num != -1)                   //  -1作为标志字符
	{
		root = new treeNode;
		root->value = num;
		createBinaryTree(root->left);
		createBinaryTree(root->right);
	}
	else
		root = nullptr;
}
// 输入:1 2 3 -1 -1 4 -1 -1 5 6 -1 -1 -1 
// 输出:前序遍历:123456  中序遍历:324165  后序遍历:342651

/*
//  形参为二维指针
void createBinaryTree_ptr(treeNode **root)
{
	int num;
	cin >> num;
	if (num != -1)
	{
		*root = new treeNode;
		(*root)->value = num;
		createBinaryTree_ptr(&((*root)->left));
		createBinaryTree_ptr(&((*root)->right));
	}
	else
		*root = nullptr;
}
*/

(2) 输入数组或vector形参

void createBinaryTree_vector(treeNode *&root, vector<int>::iterator &it)
{

	if ((*it) != -1)
	{
		root = new treeNode;
		root->value = *it;
		createBinaryTree_vector(root->left, ++it);
		createBinaryTree_vector(root->right, ++it);
	}
	else
		root = nullptr;
}

猜你喜欢

转载自blog.csdn.net/lizhentao0707/article/details/80745911