📌  相关文章
📜  二叉树中长度相等的根到叶路径

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

给定一棵二叉树,打印具有相等长度的根到叶路径的数量。

例子:

Input : Root of below tree
                   10
                  /   \
                8      2
              /  \    /  \
            3     5  2    4
Output : 4 paths are of length 3.

Input : Root of below tree 
                  10
                 /   \
               8      2
             /  \    /  \
            3    5  2    4
           /               \
          9                 1
Output : 2 paths are of length 3
         2 paths are of length 4

这个想法是遍历树并跟踪路径长度。每当我们到达叶节点时,我们都会增加哈希映射中的路径长度计数。

一旦我们遍历了树,哈希图就会有不同路径长度的计数。最后我们打印哈希映射的内容。

C++
// C++ program to count root to leaf paths of different
// lengths.
#include
using namespace std;
 
/* A binary tree node */
struct Node
{
    int data;
    struct Node* left, *right;
};
 
/* utility that allocates a new node with the
   given data and NULL left and right pointers. */
struct Node* newnode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right  = NULL;
    return (node);
}
 
// Function to store counts of different root to leaf
// path lengths in hash map m.
void pathCountUtil(Node *node, unordered_map &m,
                                             int path_len)
{
    // Base condition
    if (node == NULL)
        return;
 
    // If leaf node reached, increment count of path
    // length of this root to leaf path.
    if (node->left == NULL && node->right == NULL)
    {
         m[path_len]++;
         return;
    }
 
    // Recursively call for left and right subtrees with
    // path lengths more than 1.
    pathCountUtil(node->left, m, path_len+1);
    pathCountUtil(node->right, m, path_len+1);
}
 
// A wrapper over pathCountUtil()
void pathCounts(Node *root)
{
   // create an empty hash table
   unordered_map m;
 
   // Recursively check in left and right subtrees.
   pathCountUtil(root, m, 1);
 
   // Print all path lengths and their counts.
   for (auto itr=m.begin(); itr != m.end(); itr++)
      cout << itr->second << " paths have length "
           << itr->first << endl;
}
 
// Driver program to run the case
int main()
{
    struct Node *root = newnode(8);
    root->left    = newnode(5);
    root->right   = newnode(4);
    root->left->left = newnode(9);
    root->left->right = newnode(7);
    root->right->right = newnode(11);
    root->right->right->left = newnode(3);
    pathCounts(root);
    return 0;
}


Java
// Java program to count root to leaf
// paths of different lengths.
import java.util.HashMap;
import java.util.Map;
 
class GFG{
 
// A binary tree node
static class Node
{
    int data;
    Node left, right;
};
 
// Utility that allocates a new node
// with the given data and null left
// and right pointers.
static Node newnode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
 
// Function to store counts of different
// root to leaf path lengths in hash map m.
static void pathCountUtil(Node node,
        HashMap m, int path_len)
{
     
    // Base condition
    if (node == null)
        return;
 
    // If leaf node reached, increment count
    // of path length of this root to leaf path.
    if (node.left == null && node.right == null)
    {
        if (!m.containsKey(path_len))
            m.put(path_len, 0);
             
        m.put(path_len, m.get(path_len) + 1);
         
        return;
    }
 
    // Recursively call for left and right
    // subtrees with path lengths more than 1.
    pathCountUtil(node.left, m, path_len + 1);
    pathCountUtil(node.right, m, path_len + 1);
}
 
// A wrapper over pathCountUtil()
static void pathCounts(Node root)
{
     
    // Create an empty hash table
    HashMap m = new HashMap<>();
 
    // Recursively check in left and right subtrees.
    pathCountUtil(root, m, 1);
     
    // Print all path lengths and their counts.
    for(Map.Entry entry : m.entrySet())
    {
        System.out.printf("%d paths have length %d\n",
                          entry.getValue(),
                          entry.getKey());
    }
}
 
// Driver code
public static void main(String[] args)
{
    Node root = newnode(8);
    root.left = newnode(5);
    root.right = newnode(4);
    root.left.left = newnode(9);
    root.left.right = newnode(7);
    root.right.right = newnode(11);
    root.right.right.left = newnode(3);
     
    pathCounts(root);
}
}
 
// This code is contributed by sanjeev2552


Python3
# Python3 program to count root to leaf
# paths of different lengths.
     
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
class newnode:
 
    # Construct to create a newNode
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
         
# Function to store counts of different
# root to leaf path lengths in hash map m.
def pathCountUtil(node, m,path_len) :
 
    # Base condition
    if (node == None) :
        return
 
    # If leaf node reached, increment count of
    # path length of this root to leaf path.
    if (node.left == None and node.right == None):    
        if path_len[0] not in m:
            m[path_len[0]] = 0
        m[path_len[0]] += 1
        return
 
    # Recursively call for left and right
    # subtrees with path lengths more than 1.
    pathCountUtil(node.left, m, [path_len[0] + 1])
    pathCountUtil(node.right, m, [path_len[0] + 1])
 
# A wrapper over pathCountUtil()
def pathCounts(root) :
 
    # create an empty hash table
    m = {}
    path_len = [1]
     
    # Recursively check in left and right subtrees.
    pathCountUtil(root, m, path_len)
 
    # Print all path lengths and their counts.
    for itr in sorted(m, reverse = True):
        print(m[itr], " paths have length ", itr)
 
# Driver Code
if __name__ == '__main__':
 
    root = newnode(8)
    root.left = newnode(5)
    root.right = newnode(4)
    root.left.left = newnode(9)
    root.left.right = newnode(7)
    root.right.right = newnode(11)
    root.right.right.left = newnode(3)
    pathCounts(root)
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#
// C# program to count root to leaf
// paths of different lengths.
using System;
using System.Collections.Generic;
class GFG
{
 
  // A binary tree node
  public
    class Node
    {
      public
 
        int data;
      public
 
        Node left,
      right;
    };
 
  // Utility that allocates a new node
  // with the given data and null left
  // and right pointers.
  static Node newnode(int data)
  {
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
  }
 
  // Function to store counts of different
  // root to leaf path lengths in hash map m.
  static void pathCountUtil(Node node,
                            Dictionary m,
                            int path_len)
  {
 
    // Base condition
    if (node == null)
      return;
 
    // If leaf node reached, increment count
    // of path length of this root to leaf path.
    if (node.left == null && node.right == null)
    {
      if (!m.ContainsKey(path_len))
        m.Add(path_len, 1);
      else
        m[path_len] = m[path_len] + 1;
 
      return;
    }
 
    // Recursively call for left and right
    // subtrees with path lengths more than 1.
    pathCountUtil(node.right, m, path_len + 1);
    pathCountUtil(node.left, m, path_len + 1);
  }
 
  // A wrapper over pathCountUtil()
  static void pathCounts(Node root)
  {
 
    // Create an empty hash table
    Dictionary m = new Dictionary();
 
    // Recursively check in left and right subtrees.
    pathCountUtil(root, m, 1);
 
    // Print all path lengths and their counts.
    foreach(KeyValuePair entry in m)
    {
      Console.WriteLine(entry.Value
                        + " paths have length "
                        + entry.Key);
    }
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    Node root = newnode(8);
    root.left = newnode(5);
    root.right = newnode(4);
    root.left.left = newnode(9);
    root.left.right = newnode(7);
    root.right.right = newnode(11);
    root.right.right.left = newnode(3);
 
    pathCounts(root);
  }
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:

1 paths have length 4
2 paths have length 3

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