![](/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.