[英]Inserting an element in Binary Tree
試圖通過網絡進行大量探索,但可以得到任何幫助,Everywhere就像在Binary Search樹中添加一個節點一樣。
問題:請求用於將節點添加到二叉樹的算法和代碼片段。 (或指向我更正網址)
假設:根據我的理解, 二叉樹和二叉搜索樹是不同的? 如果我錯了,請糾正我。
(請求:如果您正在編寫代碼片段,請使用適當的變量名稱,這有助於理解)
例如:二叉樹
5 7 3 x1 x2 x3
5
7 3
x1 x2 x3
二進制搜索樹5 7 3 2 4 6
5
3 7
2 4 6
insert(int key, struct node **root)
{
if( NULL == *root )`
{
*root = (struct node*) malloc( sizeof( struct node ) );`
(*root)->data = key;
(*root)->left = NULL;
(*root)->right = NULL;
}
else if(key < (*root)->data)
{
insert( key, &(*root)->left );
}
else if(key > (*root)->data)
{
insert( key, &(*root)->right );
}
}
二叉樹和二進制搜索樹之間的區別在於,雖然它們都有限制,每個節點最多可以有2個子節點,但二進制搜索樹(BST)的左子節點也必須具有相同或更小的值,並且其正確的孩子必須具有更大或相等的價值。 這就是為什么它被稱為“搜索”樹,因為所有內容都是按數字排序的,並且它有一個O(logn)運行時間用於搜索。
因為不需要成為BST,所以可以將二叉樹存儲在向量(數組)中。 當您插入到矢量中時,您將按照水平順序方式構建二叉樹。 代碼如下:
// typedef the node struct to NODE
// nodeVector similar to STL's vector class
insert(int key, NODE** nodeVector)
{
NODE *newNode = (NODE*) malloc( sizeof( NODE ) );
newNode->data = key;
newNode->left = NULL;
newNode->right = NULL;
// add newNode to end of vector
int size = nodeVector->size();
nodeVector->push_back(newNode);
// if newNode is not root node
if(nodeVector->size() > 1)
{
// set parent's child values
Node* parent = (size/2)-1; // take advantage of integer division instead of using floor()
if (parent->left == NULL)
{
parent->left = newNode;
}
else
{
parent->right = newNode;
}
}
}
Queue數據結構可用於將元素插入到二叉樹中,因為在二進制樹中,節點的順序不會被維護,因此我們將在找到任何null時立即插入節點。 使用Queue,我們將遍歷Level Order Traversal中的二叉樹。
struct Treenode* temp;
Q = CreateQueue();
EnQueue(Q,root);
while(!IsEmptyQueue(Q))
{
temp = DeQueue(Q);
if(temp->left)
EnQueue(Q,temp->left);
else
{
temp->left=newNode;
DeleteQueue(Q);
return;
}
if(temp->right)
EnQueue(Q,temp->right);
else
{
temp->right=newNode;
DeleteQueue(Q);
return;
}
}
既然如此,我無法評論我寫這篇文章。
上面的二叉樹插入函數的答案是錯誤的。
假設0,1,2,3,4,5順序通過插入函數,
它的生成樹就像
0
/
1
\
2
/
3
\
4
/
5`<br/>
其中inorder遍歷將是1 3 5 4 2 0
而答案應該是
0
/ \
1 2
/ \ /
3 4 5
其中inorder遍歷將是3 1 4 0 5 2。
既然我也面臨同樣的問題,我想通過網絡提出以下解決方案: -
您可以使用隊列來存儲我們想要放置新節點的當前節點,就像我們在級別順序遍歷中那樣,然后我們逐級插入節點。
以下鏈接可能會幫助您: -
http://www.geeksforgeeks.org/linked-complete-binary-tree-its-creation/
我發布這個作為答案,因為我沒有必要的聲譽發表評論。 除了bagelboy之外,所有其他人都誤將樹誤解為二進制搜索樹或完整二叉樹。 問題是簡單的Binary Tree和Bagelboy的答案看起來是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.