我很难让插入功能正常工作。 cout语句与我的作业不匹配。如果我尝试插入5,我会得到<form action="https://formmail.servage.net/" method=POST>
<input type=hidden name="id" value="28939">
<input type=hidden name="subject" value="FORM SUBJECT">
<input type=text placeholder="E-Mail" onfocus="this.placeholder = ''" onblur="this.placeholder = 'E-Mail'" name="E-MAIL"><p>
<input type=text placeholder="Name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Name'" name="NAME"><p>
<input type=text placeholder="City" onfocus="this.placeholder = ''" onblur="this.placeholder = 'City'" name="CITY"><p>
<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }" name="FEEDBACK" id=text rows=5 placeholder="Message" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Message'"></textarea> <br><br>
Push enter
</form>
,但它应该是inserted: 5 right child of: 3
有人可以帮助我吗?
inserted: 5 right child of: 22
}
答案 0 :(得分:0)
插入代码存在一些问题:
NULL
以下代码应该适合您
//The following code assumes the following definition of Node
struct Node {
Node(int val, Node* l, Node* r):key(val),left(l),right(r){}
int key;
Node* left;
Node* right;
}
// Returns the root of the tree after inserting val into tree (no duplicates)
Node * insert (Node * root, int val){
if (root == NULL) return new Node(val, NULL, NULL);
if (root->key == val) return root;
if (root->key > val) return insert(root->left, val);
return insert(root->right, val);
}
上面的代码递归地定义了insert。基本情况:树是空的。插入新值作为根。如果root是密钥,那么你就完成了(没有重复的密钥)。否则,将值插入左侧或右侧子树(如果值小于root-&gt;键则为左侧,否则为右侧)。
或者您可以使用while循环迭代定义插入。
Node * insert (Node * root, int val){
// is this an empty tree?
if (root == NULL) return new Node(val, NULL, NULL);
Node* tmp = root;
while (tmp != null){
if (tmp->key == val) break;
if (tmp->key > val){
if (tmp->left == NULL){
tmp->left = new Node(val, NULL, NULL);
break;
} else {
tmp = tmp->left;
}
} else {
if (tmp->right == NULL){
tmp->right = new Node(val, NULL, NULL);
break;
} else {
tmp = tmp->right;
}
}
}
return root;
}
在任何一种情况下,您都可以使用相同的方式插入。
Node * tree1 = NULL;
tree1 = insert(tree1, 3);
tree1 = insert(tree1, 1);
tree1 = insert(tree1, 2);
tree1 = insert(tree1, 4);
后续tree1
将是以下树。
3
/ \
1 4
\
2