![](/img/trans.png)
[英]Binary tree rotate function without reference-to-pointer, pointer-to-pointer, or the function returning the new node
[英]Pointer to a new node in a Binary Tree
我正在解决在二叉树中插入节点的问题。 我有以下疑问:
1)如果要插入节点,则应返回一个指向该节点的指针,因为只有这样我们才能访问该节点,对吗?
2)那我们为什么要返回根? 我们必须相应地返回root->left
或root->right
,我在哪里错了?
struct node* insert(struct node* root, int data)
{
if (root == NULL) //If the tree is empty, return a new,single node
return newNode(data);
else
{
//Otherwise, recur down the tree
if (data <= root->data)
root->left = insert(root->left, data);
else
root->right = insert(root->right, data);
return root;
}
}
3)上面的代码返回的根是否是由于递归而更改过的根?
您误解了返回值。
此insert
函数的返回值是一个指向现在已插入data
的子树的指针。 如果传入的root
为空,则这是一个新的1节点树; 如果传入的root
为非null,则返回值为相同的root
。
这使得递归更加简单。 我们简单地递归,直到我们直接进入分支的nullptr
为止。 然后递归停止,返回值设置父级的left
节点或right
节点。
要创建全新的树,请输入:
node* new_tree = insert(nullptr, 7);
在您输入的现有树中插入内容:
existing_tree = insert(existing_tree, 7);
或同等
insert(existing_tree, 7);
只要existing_tree
不为null。
该函数的“双重使用”(用于创建和修改树)可能会造成混淆,但是它使特定的递归使用不那么冗长,并且使“空树为nullptr”和“总是做exist_tree existing_tree = insert(existing_tree, val);
“是使空树作为空树起作用的规则。
但是,这是一种非常C的处理方式。
一种更C ++的处理方式是:
std::unique_ptr<node> insert(std::unique_ptr<node> root, int data)
{
if (root == nullptr) //If the tree is empty, return a new,single node
return std::make_unique<node>(data);
else
{
//Otherwise, recur down the tree
if (data <= root->data)
root->left = insert(std::move(root->left), data);
else
root->right = insert(std::move(root->right), data);
return std::move(root);
}
}
进出函数的数据流更为明确,我们假设node
有一个采用data
的构造函数。
此递归插入应始终返回树的根节点。 仅仅因为您读取了return root
并不意味着原始函数调用已完成执行,仅意味着第n个递归已完成。 递归调用已全部压入堆栈,因此必须在原始调用者收到返回值之前全部解决。
您可以通过find
插入的值来返回到插入的节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.