[英]Binary tree C++ basics
void BinarySearchTree::insert(int d)
{
tree_node* t = new tree_node;
tree_node* parent;
t->data = d;
t->left = NULL;
t->right = NULL;
parent = NULL;
// is this a new tree?
if(isEmpty()) root = t;
else
{
//Note: ALL insertions are as leaf nodes
tree_node* curr;
curr = root;
// Find the Node's parent
while(curr)
{
parent = curr;
if(t->data > curr->data) curr = curr->right;
else curr = curr->left;
}
if(t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
}
Questions: 问题:
Why do I need to allocate memory for tree_node* t; 为什么我需要为tree_node * t分配内存; using new but not for tree_node* parent; 使用new但不用于tree_node *父级; ? ?
What exactly is tree_node* what does it look like in memory and what does it do? tree_node *到底是什么,在内存中看起来是什么,它是做什么的?
Can someone explain to me the -> operator and how it works? 有人可以向我解释->运算符及其工作原理吗?
Why do I need to allocate memory for tree_node* t; 为什么我需要为tree_node * t分配内存; using new but not for tree_node* parent;? 使用新的但不用于tree_node *父级?
You don't need to, but it's part of the logic. 您不需要 ,但这是逻辑的一部分。 t
represents the new node you're inserting, so you need to create it first (which is done by the new
). t
表示您要插入的新节点,因此需要首先创建它(由new
来完成)。 You don't allocate memory for parent
because it will refer to an already existing node: 您不parent
节点分配内存,因为它将引用已经存在的节点:
while(curr)
{
parent = curr;
//...
What exactly is tree_node* what does it look like in memory and what does it do? tree_node *到底是什么,在内存中看起来是什么,它是做什么的?
No way to tell (it should be defined somewhere), but it's probably a structure like so: 无法分辨(应该在某处定义),但是可能是这样的结构:
struct tree_node
{
tree_node* left;
tree_node* right;
int data;
}
Can someone explain to me the -> operator and how it works? 有人可以向我解释->运算符及其工作原理吗?
It's for accessing object members through a pointer. 它用于通过指针访问对象成员。 If you have Class* x
, then x->a
is equivalent to (*x).a
. 如果您具有Class* x
,则x->a
等效于(*x).a
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.