It's a function to bulid a binary tree,but it can't work,can someone tell me what's wrong with my code
typedef struct treeNode* BT;
struct treeNode {
int val;
treeNode* left;
treeNode* right;
};
BT createTree(BT root) {
int data = 0;
cin >> data;
if (data == -1) {
return nullptr;
}
root = new treeNode;
root->val = data;
createTree(root->left);
createTree(root->right);
return root;
}
You're ignoring the result of createTree(root->left);
and createTree(root->right);
What's more, in your implementation the argument root
is meaningless. You're not using it at all. Code below should work.
BT createTree() {
int data = 0;
BT root;
cin >> data;
if (data == -1) {
return nullptr;
}
root = new treeNode;
root->val = data;
root->left = createTree();
root->right = createTree();
return root;
}