[英]Why is the root variable in a Binary Tree a pointer the node and not the node itself?
I am trying to implement a Binary Tree in C++ and was going through some tutorials online to learn more about it.我正在尝试用 C++ 实现一个二叉树,并且正在网上浏览一些教程以了解更多信息。
I noticed that all tutorials mention that the root variable of the Binary Tree should be a pointer to the root node and not the node itself.我注意到所有教程都提到二叉树的根变量应该是指向根节点的指针,而不是节点本身。 Example code:
示例代码:
struct Node {
int data;
Node *left, *right;
};
class BinaryTree {
private:
Node *root;
};
Why not make the root variable Node root
instead and when I insert a node in the binary tree I can assign values to the root?为什么不让根变量
Node root
代替,当我在二叉树中插入一个节点时,我可以为根分配值?
Since the root node is also a node, it can be deleted.由于根节点也是一个节点,所以可以将其删除。 If it is not a pointer, you would have to start copying nodes instead of just moving pointers.
如果它不是指针,则必须开始复制节点,而不仅仅是移动指针。
It could also be nullptr
if the tree is empty如果树是空的,它也可能是
nullptr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.