What is wrong in taking input like this for a generic tree? Also how to make a dynamic array for children instead of size 100

class TreeNode {
public:
	int data;
	int n_children = 0;
	TreeNode* children[100];

	TreeNode (int data) {
		this -> data = data;
	}
};

TreeNode* inputGenericTree() {
	int data; cin >> data;
	int n_child; cin >> n_child;
	TreeNode* root = new TreeNode(data);
	root -> n_children = n_child;
	
	int i;
	rep (i, 0, n_child) {
		root -> children[i] = inputGenericTree();
	}

	return root;
}

@Avi-Kasliwal-315786729062203 it is mentioned that the number of children will be at most 2, so you can work with a binary tree only.

For dynamic memory allocation i’d suggest using a vector instead of arrays.

thats fine, but what if I want user to tell me n_children, then is my code correct?

@Avi-Kasliwal-315786729062203 it seems to be correct, You should make a vector of nodes (for children) and initialise everything with NULL.

1 Like