在C ++程序中删除值为x的叶节点

在本教程中,我们将学习如何从具有给定值的树中删除叶节点。

让我们看看解决问题的步骤。

  • 为二叉树编写一个结构节点。

  • 编写一个函数来遍历树(顺序,前顺序,后顺序)并打印所有数据。

  • 通过使用struct创建节点来初始化树。

  • 初始化x值。

  • 编写函数以删除具有给定值的叶节点。它接受两个参数根节点和x值。

    • 如果根为空,则返回。

    • 删除后,用新的根替换根的左节点。

    • 与根的右节点相同。

    • 如果当前根节点数据等于x并且它是叶节点,则返回空指针。

    • 返回根节点

示例

让我们看一下代码。

#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);
   // 用x检查当前节点数据
   if (root->data == x && root->left == NULL && root->right == NULL) {
      // 删除节点
      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

结论