📌  相关文章
📜  删除给定节点后打印二叉树的森林

📅  最后修改于: 2021-10-27 07:18:45             🧑  作者: Mango

给定一个二叉树和一个由要删除的节点值组成的数组arr[] ,任务是在删除节点后打印森林的中序遍历。

例子:

处理方法:按照以下步骤解决问题:

  1. 执行二叉树的后序遍历。
  2. 对于每个节点,检查它是否包含要删除的值。
  3. 如果发现为真,则将其子项存储为森林的根。通过中序遍历打印森林。

下面是上述方法的实现:

C++
10
       /  \
      20   30
     / \    \
    4   5    7


Java
1
       /   \
      5     6
     /       \
    10       12


Python3
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Stores the nodes to be deleted
unordered_map mp;
 
// Structure of a Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Function to check whether the node
// needs to be deleted or not
bool deleteNode(int nodeVal)
{
    return mp.find(nodeVal) != mp.end();
}
 
// Function to perform tree pruning
// by performing post order traversal
Node* treePruning(Node* root, vector& result)
{
    if (root == NULL)
        return NULL;
 
    root->left = treePruning(root->left, result);
    root->right = treePruning(root->right, result);
 
    // If the node needs to be deleted
    if (deleteNode(root->key)) {
 
        // Store the its subtree
        if (root->left) {
            result.push_back(root->left);
        }
        if (root->right) {
            result.push_back(root->right);
        }
        return NULL;
    }
 
    return root;
}
 
// Perform Inorder Traversal
void printInorderTree(Node* root)
{
    if (root == NULL)
        return;
 
    printInorderTree(root->left);
    cout << root->key << " ";
    printInorderTree(root->right);
}
 
// Function to print the forests
void printForests(Node* root, int arr[], int n)
{
    for (int i = 0; i < n; i++) {
        mp[arr[i]] = true;
    }
 
    // Stores the remaining nodes
    vector result;
 
    if (treePruning(root, result))
        result.push_back(root);
 
    // Print the inorder traversal of Forests
    for (int i = 0; i < result.size(); i++) {
        printInorderTree(result[i]);
        cout << endl;
    }
}
 
// Driver Code
int main()
{
 
    Node* root = newNode(1);
    root->left = newNode(12);
    root->right = newNode(13);
    root->right->left = newNode(14);
    root->right->right = newNode(15);
    root->right->left->left = newNode(21);
    root->right->left->right = newNode(22);
    root->right->right->left = newNode(23);
    root->right->right->right = newNode(24);
 
    int arr[] = { 14, 23, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printForests(root, arr, n);
}


C#
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Stores the nodes to be deleted
static HashMap mp  = new HashMap<>();
 
// Structure of a Tree node
static class Node
{
    int key;
    Node left, right;
};
 
// Function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
 
// Function to check whether the node
// needs to be deleted or not
static boolean deleteNode(int nodeVal)
{
    return mp.containsKey(nodeVal);
}
 
// Function to perform tree pruning
// by performing post order traversal
static Node treePruning(Node root,
                        Vector result)
{
    if (root == null)
        return null;
 
    root.left = treePruning(root.left, result);
    root.right = treePruning(root.right, result);
 
    // If the node needs to be deleted
    if (deleteNode(root.key))
    {
 
        // Store the its subtree
        if (root.left != null)
        {
            result.add(root.left);
        }
        if (root.right != null)
        {
            result.add(root.right);
        }
        return null;
    }
    return root;
}
 
// Perform Inorder Traversal
static void printInorderTree(Node root)
{
    if (root == null)
        return;
 
    printInorderTree(root.left);
    System.out.print(root.key + " ");
    printInorderTree(root.right);
}
 
// Function to print the forests
static void printForests(Node root,
                         int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        mp.put(arr[i], true);
    }
 
    // Stores the remaining nodes
    Vector result  = new Vector<>();
 
    if (treePruning(root, result) != null)
        result.add(root);
 
    // Print the inorder traversal of Forests
    for (int i = 0; i < result.size(); i++)
    {
        printInorderTree(result.get(i));
        System.out.println();
    }
}
 
// Driver Code
public static void main(String[] args)
{
 
    Node root = newNode(1);
    root.left = newNode(12);
    root.right = newNode(13);
    root.right.left = newNode(14);
    root.right.right = newNode(15);
    root.right.left.left = newNode(21);
    root.right.left.right = newNode(22);
    root.right.right.left = newNode(23);
    root.right.right.right = newNode(24);
 
    int arr[] = { 14, 23, 1 };
    int n = arr.length;
    printForests(root, arr, n);
}
}
 
// This code is contributed by Rajput-Ji


Javascript
# Python3 Program to implement
# the above approach
  
# Stores the nodes to be deleted
mp = dict()
  
# Structure of a Tree node
class Node:
     
    def __init__(self, key):
         
        self.key = key
        self.left = None
        self.right = None
     
# Function to create a new node
def newNode(key):
 
    temp = Node(key)
    return temp
  
# Function to check whether the node
# needs to be deleted or not
def deleteNode(nodeVal):
 
    if nodeVal in mp:
        return True
    else:
        return False
 
# Function to perform tree pruning
# by performing post order traversal
def treePruning( root, result):
 
    if (root == None):
        return None;
  
    root.left = treePruning(root.left, result);
    root.right = treePruning(root.right, result);
  
    # If the node needs to be deleted
    if (deleteNode(root.key)):
  
        # Store the its subtree
        if (root.left):
            result.append(root.left);
         
        if (root.right):
            result.append(root.right);
         
        return None;
     
    return root;
 
# Perform Inorder Traversal
def printInorderTree(root):
 
    if (root == None):
        return;
  
    printInorderTree(root.left);
    print(root.key, end=' ')
    printInorderTree(root.right);
  
# Function to print the forests
def printForests(root, arr, n):
    for i in range(n):   
        mp[arr[i]] = True;
     
    # Stores the remaining nodes
    result = []
  
    if (treePruning(root, result)):
        result.append(root);
  
    # Print the inorder traversal of Forests
    for i in range(len(result)):
     
        printInorderTree(result[i]);
        print()
         
# Driver Code
if __name__=='__main__':
  
    root = newNode(1);
    root.left = newNode(12);
    root.right = newNode(13);
    root.right.left = newNode(14);
    root.right.right = newNode(15);
    root.right.left.left = newNode(21);
    root.right.left.right = newNode(22);
    root.right.right.left = newNode(23);
    root.right.right.right = newNode(24);
  
    arr = [ 14, 23, 1 ]
    n = len(arr)
    printForests(root, arr, n);
 
# This code is contributed by rutvik_56


输出:
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Stores the nodes to be deleted
static Dictionary mp = new Dictionary();
 
// Structure of a Tree node
class Node
{
    public int key;
    public Node left, right;
};
 
// Function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
 
// Function to check whether the node
// needs to be deleted or not
static bool deleteNode(int nodeVal)
{
    return mp.ContainsKey(nodeVal);
}
 
// Function to perform tree pruning
// by performing post order traversal
static Node treePruning(Node root,
                        List result)
{
    if (root == null)
        return null;
 
    root.left = treePruning(root.left, result);
    root.right = treePruning(root.right, result);
 
    // If the node needs to be deleted
    if (deleteNode(root.key))
    {
 
        // Store the its subtree
        if (root.left != null)
        {
            result.Add(root.left);
        }
        if (root.right != null)
        {
            result.Add(root.right);
        }
        return null;
    }
    return root;
}
 
// Perform Inorder Traversal
static void printInorderTree(Node root)
{
    if (root == null)
        return;
 
    printInorderTree(root.left);
    Console.Write(root.key + " ");
    printInorderTree(root.right);
}
 
// Function to print the forests
static void printForests(Node root,
                         int []arr, int n)
{
    for(int i = 0; i < n; i++)
    {
        mp.Add(arr[i], true);
    }
 
    // Stores the remaining nodes
    List result = new List();
 
    if (treePruning(root, result) != null)
        result.Add(root);
 
    // Print the inorder traversal of Forests
    for(int i = 0; i < result.Count; i++)
    {
        printInorderTree(result[i]);
        Console.WriteLine();
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    Node root = newNode(1);
    root.left = newNode(12);
    root.right = newNode(13);
    root.right.left = newNode(14);
    root.right.right = newNode(15);
    root.right.left.left = newNode(21);
    root.right.left.right = newNode(22);
    root.right.right.left = newNode(23);
    root.right.right.right = newNode(24);
 
    int []arr = { 14, 23, 1 };
    int n = arr.Length;
    printForests(root, arr, n);
}
}
 
// This code is contributed by Amit Katiyar

时间复杂度: O(N)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程