用 C++ 程序删除值等于 x 的叶节点
在本教程中,我们将了解如何从给定值的树中删除叶节点。
我们看看解决这个问题的步骤。
针对二叉树编写一个结构 Node。
编写一个函数来遍历(中序、前序、后序)树并打印所有数据。
通过用结构创建节点来初始化树。
初始化 x 值。
编写一个函数来删除具有给定值的叶节点。它接受两个参数根节点和 x 值。
如果根节点为 null,那么返回。
删除后用新根节点替换根节点的左节点。
根节点的右节点也一样。
如果当前根节点数据等于 x 且它是叶节点,则返回一个 null 指针。
返回根节点
示例
让我们看看代码。
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode(int data) {
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
Node* deleteLeafNodes(Node* root, int x) {
if (root == NULL) {
return nullptr;
}
root->left = deleteLeafNodes(root->left, x);
root->right = deleteLeafNodes(root->right, x);
// checking the current node data with x
if (root->data == x && root->left == NULL && root->right == NULL) {
// deleting the node
return nullptr;
}
return root;
}
void inorder(Node* root) {
if (root == NULL) {
return;
}
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
int main(void) {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->right = newNode(5);
root->right->left = newNode(4);
root->right->right->left = newNode(4);
root->right->right->right = newNode(4);
deleteLeafNodes(root, 4);
cout << "Tree: ";
inorder(root);
cout << endl;
return 0;
}输出
如果你执行上面的代码,你将得到以下结果。
Tree: 3 2 1 3 5
结论
如果您对本教程有任何疑问,请在评论部分中提出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP