📌  相关文章
📜  清空给定二叉树的每一步需要移除的叶节点数

📅  最后修改于: 2021-09-08 15:08:02             🧑  作者: Mango

给定一棵二叉树,任务是在每次操作期间移除二叉树的叶节点并打印计数。

例子:

朴素的方法:解决这个问题的最简单的方法是为每个操作重复遍历树并打印当前存在于二叉树中的叶节点的计数并从二叉树中删除所有的叶节点。

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

有效的方法:为了优化上述方法,其思想是观察到,除非节点的两个子节点都已被删除,否则不会删除节点。因此,可以确定在哪一步删除节点,这将等于1 + 从该节点到以该节点为根的子树中任何叶节点的最大路径长度。请按照以下步骤解决此问题:

  • 初始化一个 Map,比如M ,以存储从树中每次删除时的叶节点。
  • 按照以下步骤对给定的二叉树执行 DFS 遍历:
    • 检查给定节点是否为NULL 。如果发现为真,则返回0
    • 否则,递归调用的左边右边的节点和存储从它返回的值。
    • 在每个节点的上述步骤中,找到最大高度,例如maxHeight ,当每个节点将成为叶节点时(1 + 左右递归调用返回的值的最大值)
    • 将当前节点插入 Map M的 key maxHeight 处
  • 完成上述步骤后,打印每次删除后存储在Map中的叶节点数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Structure of a
// Binary Tree Node
struct Node {
    int data;
    Node *left, *right;
};
 
// Function to allocate
// a new tree node
Node* newNode(int data)
{
    Node* node = new Node;
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return node;
}
 
// Function to find the maximum height
// from leaf in the subtree rooted at
// current node and add that to hashmap
int maxHeightToLeafUTIL(
    Node* curr, map >& mp)
{
    if (curr == NULL) {
        return 0;
    }
 
    // Max height to leaf in left subtree
    int leftLeaf
        = maxHeightToLeafUTIL(curr->left, mp);
 
    // Max height to leaf in right subtree
    int rightLeaf
        = maxHeightToLeafUTIL(curr->right, mp);
 
    // Max height to leaf in current subtree
    int maxHeightSubtree
        = 1 + max(leftLeaf, rightLeaf);
 
    // Adding current node to the Map
    mp[maxHeightSubtree].push_back(
        curr->data);
 
    return maxHeightSubtree;
}
 
// Function to find the count of leaf nodes
// by repeatedly removing the leaf nodes
void printAndDelete(Node* root)
{
 
    // Stores the leaf deletion with
    // each iteration
    map > mp;
 
    // Function Call to find the order
    // of deletion of nodes
    maxHeightToLeafUTIL(root, mp);
 
    // Printing the map values
    for (auto step : mp) {
 
        cout << mp[step.first].size() << " ";
    }
}
 
// Driver code
int main()
{
    // Given Binary Tree
    Node* root = newNode(2);
    root->right = newNode(7);
    root->right->right = newNode(6);
    root->left = newNode(5);
    root->left->left = newNode(1);
    root->left->right = newNode(8);
    root->left->right->left = newNode(3);
    root->left->right->right = newNode(4);
 
    /*
    Input :
         2
       /   \
      5     7
     / \     \
    1   8     6
       / \
      3   4
*/
 
    // Function Call
    printAndDelete(root);
 
    return 0;
}
 
// This code is contributed by pragup


Java
// Java program for the above approach
import java.util.*;
 
// A binary tree node
class Node
{
  int data;
  Node left, right;
  Node(int item)
  {
    data = item;
    left = right = null;
  }
}
 
class GFG
{
  Node root;
 
  // Function to find the maximum height
  // from leaf in the subtree rooted at
  // current node and add that to hashmap
  static int maxHeightToLeafUTIL(
    Node curr, Map > mp)
  {
    if (curr == null)
    {
      return 0;
    }
 
    // Max height to leaf in left subtree
    int leftLeaf
      = maxHeightToLeafUTIL(curr.left, mp);
 
    // Max height to leaf in right subtree
    int rightLeaf
      = maxHeightToLeafUTIL(curr.right, mp);
 
    // Max height to leaf in current subtree
    int maxHeightSubtree
      = 1 + Math.max(leftLeaf, rightLeaf);
 
    // Adding current node to the Map
    if(!mp.containsKey(maxHeightSubtree))
    {
      mp.put(maxHeightSubtree, new ArrayList<>());  
    }
 
    mp.get(maxHeightSubtree).add(curr.data);
    return maxHeightSubtree;
  }
 
  // Function to find the count of leaf nodes
  // by repeatedly removing the leaf nodes
  static void printAndDelete(Node root)
  {
 
    // Stores the leaf deletion with
    // each iteration
    Map > mp=new HashMap<>();
 
    // Function Call to find the order
    // of deletion of nodes
    maxHeightToLeafUTIL(root, mp);
 
    // Printing the map values
    for (Map.Entry> k:mp.entrySet())
    {
      System.out.print(k.getValue().size() + " ");
    }
  }
 
  // Driver code
  public static void main (String[] args)
  {
 
    GFG tree = new GFG();
 
    tree.root = new Node(2);
    tree.root.left = new Node(5);
    tree.root.right = new Node(7);
    tree.root.right.right = new Node(6);
    tree.root.left.left = new Node(1);
    tree.root.left.right = new Node(8);
    tree.root.left.right.left = new Node(3);
    tree.root.left.right.right = new Node(4);
 
    /*
    Input :
         2
       /   \
      5     7
     / \     \
    1   8     6
       / \
      3   4
*/
 
    // Function Call
    printAndDelete(tree.root);
  }
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
 
# Tree node structure used in the program
class Node:
     
    def __init__(self, x):
         
        self.data = x
        self.left = None
        self.right = None
 
# Function to find the maximum height
# from leaf in the subtree rooted at
# current node and add that to hashmap
def maxHeightToLeafUTIL(curr):
     
    global mp
 
    if (curr == None):
        return 0
 
    # Max height to leaf in left subtree
    leftLeaf = maxHeightToLeafUTIL(curr.left)
 
    # Max height to leaf in right subtree
    rightLeaf = maxHeightToLeafUTIL(curr.right)
 
    # Max height to leaf in current subtree
    maxHeightSubtree = 1 + max(leftLeaf, rightLeaf)
 
    # Adding current node to the Map
    mp[maxHeightSubtree].append(curr.data)
 
    return maxHeightSubtree
 
# Function to find the count of leaf nodes
# by repeatedly removing the leaf nodes
def printAndDelete(root):
     
    global mp
     
    # Function Call to find the order
    # of deletion of nodes
    maxHeightToLeafUTIL(root)
 
    for step in mp:
        if len(step):
            print(len(step), end = " ")
 
# Driver code
if __name__ == '__main__':
     
    mp = [[] for i in range(1000)]
     
    # Given Binary Tree
    root = Node(2)
    root.right = Node(7)
    root.right.right = Node(6)
    root.left = Node(5)
    root.left.left = Node(1)
    root.left.right = Node(8)
    root.left.right.left = Node(3)
    root.left.right.right = Node(4)
    #
    #    
    #     Input :
    #          2
    #        /   \
    #       5     7
    #      / \     \
    #     1   8     6
    #        / \
    #       3   4
 
    # Function Call
    printAndDelete(root)
     
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
// A binary tree node
public class Node
{
  public int data;
  public Node left, right;
  public Node(int item)
  {
    data = item;
    left = right = null;
  }
}
 
public class GFG{
     
    Node root;
  
  // Function to find the maximum height
  // from leaf in the subtree rooted at
  // current node and add that to hashmap
  static int maxHeightToLeafUTIL(
    Node curr, Dictionary > mp)
  {
    if (curr == null)
    {
      return 0;
    }
  
    // Max height to leaf in left subtree
    int leftLeaf
      = maxHeightToLeafUTIL(curr.left, mp);
  
    // Max height to leaf in right subtree
    int rightLeaf
      = maxHeightToLeafUTIL(curr.right, mp);
  
    // Max height to leaf in current subtree
    int maxHeightSubtree
      = 1 + Math.Max(leftLeaf, rightLeaf);
  
    // Adding current node to the Map
    if(!mp.ContainsKey(maxHeightSubtree))
    {
      mp.Add(maxHeightSubtree, new List()); 
    }
  
    mp[maxHeightSubtree].Add(curr.data);
    return maxHeightSubtree;
  }
  
  // Function to find the count of leaf nodes
  // by repeatedly removing the leaf nodes
  static void printAndDelete(Node root)
  {
  
    // Stores the leaf deletion with
    // each iteration
    Dictionary > mp=new Dictionary >();
  
    // Function Call to find the order
    // of deletion of nodes
    maxHeightToLeafUTIL(root, mp);
  
    // Printing the map values
    foreach(KeyValuePair> k in mp)
    {
      Console.Write(k.Value.Count + " ");
    }
  }
  
  // Driver code
     
    static public void Main (){
         
        GFG tree = new GFG();
  
    tree.root = new Node(2);
    tree.root.left = new Node(5);
    tree.root.right = new Node(7);
    tree.root.right.right = new Node(6);
    tree.root.left.left = new Node(1);
    tree.root.left.right = new Node(8);
    tree.root.left.right.left = new Node(3);
    tree.root.left.right.right = new Node(4);
  
    /*
    Input :
         2
       /   \
      5     7
     / \     \
    1   8     6
       / \
      3   4
*/
  
    // Function Call
    printAndDelete(tree.root);
    }
}


Javascript


输出:
4 2 1 1

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

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