用 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
結論
如果您對本教程有任何疑問,請在評論部分中提出。
廣告