二叉搜索树中的插入操作

给定一个二叉搜索树的 根节点,我们需要将一个具有给定值的新节点插入到该 BST 中。二叉搜索树中的所有节点都具有不同的值,并且我们可以假设待插入的新值不存在于当前的 BST 中。

示例:

!Insertion-in-BST

新的键值会被插入到能够维持 BST 性质的位置上。我们从根节点开始,向下移动:如果键值较小,则向左走;如果较大,则向右走。我们持续这一过程,直到找到一个未被占据的位置,该位置可以在不违反 BST 性质的情况下放置节点,然后将其作为新的叶子节点插入。

使用递归在二叉搜索树中插入:

在 GfG 练习平台上尝试此题<img src="https://www.geeksforgeeks.org/problems/insert-a-node-in-a-bst/1" alt="redirect icon" />

C++


CODEBLOCK_a408204a

C


//Driver Code Starts

#include

#include

// Node structure

struct Node {

int data;

struct Node* left;

struct Node* right;

};

// Function prototypes

struct Node* newNode(int val);

struct Node insert(struct Node root, int key);

void levelOrder(struct Node* root);

int getHeight(struct Node* root, int h);

// Queue node for level order traversal

struct QueueNode {

struct Node* node;

int level;

struct QueueNode* next;

};

// Queue structure

struct Queue {

struct QueueNode* front;

struct QueueNode* rear;

};

// Create a new queue

struct Queue* createQueue() {

struct Queue q = (struct Queue)malloc(sizeof(struct Queue));

q->front = q->rear = NULL;

return q;

}

// Enqueue node with level

void enqueue(struct Queue q, struct Node node, int level) {

struct QueueNode temp = (struct QueueNode)malloc(sizeof(struct QueueNode));

temp->node = node;

temp->level = level;

temp->next = NULL;

if (q->rear == NULL) {

q->front = q->rear = temp;

return;

}

q->rear->next = temp;

q->rear = temp;

}

// Dequeue node

struct QueueNode dequeue(struct Queue q) {

if (q->front == NULL)

return NULL;

struct QueueNode* temp = q->front;

q->front = q->front->next;

if (q->front == NULL)

q->rear = NULL;

return temp;

}

// Check if queue is empty

int isEmpty(struct Queue* q) {

return q->front == NULL;

}

// Function to get height of tree

int getHeight(struct Node* root, int h) {

if (root == NULL)

return h – 1;

int leftH = getHeight(root->left, h + 1);

int rightH = getHeight(root->right, h + 1);

return (leftH > rightH ? leftH : rightH);

}

// Level order traversal (prints N for null)

void levelOrder(struct Node* root) {

if (root == NULL)

retu

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/26207.html
点赞
0.00 平均评分 (0% 分数) - 0