简体   繁体   English

为什么二叉树中的根变量是节点的指针而不是节点本身?

[英]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.

相关问题 C ++二叉树,修改根节点,指向根节点的指针 - C++ Binary Tree, modifying root node, pointer to pointer to root node 指向二叉树中的新节点的指针 - Pointer to a new node in a Binary Tree 二进制搜索树中的根节点为空 - Root node in Binary search tree is null 为什么即使我在另一个节点中复制了根节点,我的原始二叉搜索树也会被修改? - Why my original Binary search tree is getting modified even though I copied root node in another node? C ++:指针与指针的指针,用于在二叉树中插入节点 - C++: Pointer vs Pointer of Pointer to insert a node in a Binary Tree 指向根的二叉树指针需要被引用和取消引用。 为什么? - Binary tree pointer to the root needs to be referenced and dereferenced. Why? 根node_ptr上的二进制搜索树访问冲突 - Binary Search Tree Access Violation on root node_ptr 迭代地将新节点添加到二叉树中,根被覆盖 - Iteratively adding a new node to a binary tree, root getting overwritten 在没有节点指针作为参数的情况下遍历二进制搜索树 - In order traversal for binary search tree without node pointer as parameter 尝试在构建二进制树时创建指向父节点的指针 - Trying to create a pointer to parent node whilst building binary Tree
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM