且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何修复这些语法错误?

更新时间:2023-09-11 22:01:52

您正在切换案例中调用函数。这些需要传递现有的和类型匹配的参数。



示例:

  float  s =  1  .0f; 
// 结构节点的实例
节点头;
// 初始化
head.info = 0 跨度>;
head.left = NULL;
head.right = NULL;
// 也可以在一行中将所有标准设置为零:
// node head = {0};
// 初始化树(node *)实例
tree root =& head;

// 参数的类型为node *和float
建立(& head,s);
// 参数的类型为树(节点*)
inorder(root) );


I was asked to write a prgram that should do the following;
- build a binary search tree using arrays and pointers. The values stored at the nodes are real numbers.
- Travers the binary tree in the usual 3 ways: inorder, pre order and post oreder.

So before directly going to write the whole program, I wanted to at least write one using only pointers. Then if it works, I would add the requierd lines so that the code can build the BST either using pointers or an array depending on the users choice.

Down belowe is the code I've tried, and the probleme is that I don't know how to fix the syntax errors in the functions in the case statements.

What I have tried:

#include <iostream>
using namespace std;

struct node {
	float info;
	node * left;
	node * right;
	};

typedef node *tree;    // to store the address of the root node.

void build(node *t, float x){
	if (t == NULL){
		t = new node;
		t -> info = x;
		t -> left =   NULL;
		t -> right = NULL;
    }
	else{
		if (t -> info >= x)
			build (t -> left, x);
		else
			build(t-> right, x);
	}
}


void inorder(tree t){
	if (t -> left != NULL)
		inorder (t -> left);
	cout << t -> info <<" ";
	if (t -> right != NULL)
		inorder (t -> right);
}


void preorder(tree t){
	if (t != NULL){
		cout << t -> info <<" ";
		preorder(t -> left);
		preorder(t -> right);
	}
}

void postorder(tree t){
	if (t -> left != NULL)
		postorder(t -> left);
    if (t -> right != NULL)
    	postorder(t -> right);
    cout << t -> info <<" ";
}

int main() {
b:	cout << "Choose among the following actions" << endl;
	cout << "1. Build a binary search tree"<< endl;
	cout << "2. Traverse the tree in order"<< endl;
	cout << "3. Traverse the tree in pre order"<< endl;
	cout << "4. Traverse the tree in post order"<< endl;
	cout << "5. Quit"<< endl;

	float s;

	int choice;
	cin >> choice;

	switch(choice){
	case 1:
		build(node*,s);
		break;
	case 2:
		inorder(node*);
		break;
	case 3:
		preorder(node*);
		break;
	case 4:
		postorder(node*);
		break;
	case 5:
		goto a;
		break;
	default :
		goto b;
		break;

	}

a:	return 0;
}

You are calling functions from within your switch cases. These require passing existing and type matching parameters.

Examples:
float s = 1.0f;
// An instance of struct node
node head;
// Initialise it
head.info = 0;
head.left = NULL;
head.right = NULL;
// May do it also in a single line setting all mebers to zero: 
//node head = { 0 };
// An initialised tree (node*) instance
tree root = &head;

// Parameters are of type node* and float
build(&head, s);
// Parameter is of type tree (node*)
inorder(root);