📌  相关文章
📜  给定 N 叉树中与子树中所有叶节点的距离相等的节点数

📅  最后修改于: 2022-05-13 01:57:17.654000             🧑  作者: Mango

给定 N 叉树中与子树中所有叶节点的距离相等的节点计数

给定一个 N 叉树根,任务是找到树中非叶节点的数量,使得当前节点的子树中的所有叶节点与当前节点的距离相等。

例子:

方法:给定的问题可以通过使用后序遍历来解决。这个想法是检查从当前节点到其所有叶节点的节点数是否相同。可以按照以下步骤解决问题:

  • 在 N 叉树上应用后序遍历:
    • 如果根没有子节点,则返回 1 给父节点
    • 如果每个分支的高度相等,则将计数增加 1 并将高度 + 1 返回给父级
    • 否则返回 -1 给父级,表示分支高度不等
  • 返回计数作为答案
C++
// C++ code for the above approach
#include 
using namespace std;
class Node {
public:
    vector children;
    int val;
    // constructor
    Node(int v)
    {
        val = v;
        children = {};
    }
};
 
// Post-order traversal to find
// depth of all branches of every
// node of the tree
int postOrder(Node* root, int count[])
{
   
    // If root is a leaf node
    // then return 1
    if (root->children.size() == 0)
        return 1;
   
    // Initialize a variable height
    // calculate longest increasing path
    int height = 0;
   
    // Use recursion on all child nodes
    for (Node* child : root->children)
    {
       
        // Get the height of the branch
        int h = postOrder(child, count);
       
        // Initialize height of first
        // explored branch
        if (height == 0)
            height = h;
       
        // If branches are unbalanced
        // then store -1 in height
        else if (h == -1 || height != h)
            height = -1;
    }
   
    // Increment the value of count
    // If height is not -1
    if (height != -1)
        count[0]++;
   
    // Return the height of branches
    // including the root if height is
    // not -1 or else return -1
    return height != -1 ? height + 1 : -1;
}
 
// Function to find the number of nodes
// in the N-ary tree with their branches
// having equal height
int equalHeightBranches(Node* root)
{
   
    // Base case
    if (root == NULL)
        return 0;
   
    // Initialize a variable count
    // to store the answer
    int count[1] = { 0 };
   
    // Apply post order traversal
    // on the tree
    postOrder(root, count);
   
    // Return the answer
    return count[0];
}
// Driver code
int main()
{
    // Initialize the tree
    Node* seven = new Node(7);
    Node* seven2 = new Node(7);
    Node* five = new Node(5);
    Node* four = new Node(4);
    Node* nine = new Node(9);
    Node* one = new Node(1);
    Node* two = new Node(2);
    Node* six = new Node(6);
    Node* eight = new Node(8);
    Node* ten = new Node(10);
    Node* three = new Node(3);
    Node* mfour = new Node(-4);
    Node* mtwo = new Node(-2);
    Node* zero = new Node(0);
    three->children.push_back(mfour);
    three->children.push_back(mtwo);
    three->children.push_back(zero);
    ten->children.push_back(three);
    two->children.push_back(six);
    two->children.push_back(seven2);
    four->children.push_back(nine);
    four->children.push_back(one);
    four->children.push_back(five);
    seven->children.push_back(ten);
    seven->children.push_back(two);
    seven->children.push_back(eight);
    seven->children.push_back(four);
   
    // Call the function
    // and print the result
    cout << (equalHeightBranches(seven));
}
 
// This code is contributed by Potta Lokesh


Java
// Java implementation for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find the number of nodes
    // in the N-ary tree with their branches
    // having equal height
    public static int equalHeightBranches(Node root)
    {
 
        // Base case
        if (root == null)
            return 0;
 
        // Initialize a variable count
        // to store the answer
        int[] count = new int[1];
 
        // Apply post order traversal
        // on the tree
        postOrder(root, count);
 
        // Return the answer
        return count[0];
    }
 
    // Post-order traversal to find
    // depth of all branches of every
    // node of the tree
    public static int postOrder(
        Node root, int[] count)
    {
 
        // If root is a leaf node
        // then return 1
        if (root.children.size() == 0)
            return 1;
 
        // Initialize a variable height
        // calculate longest increasing path
        int height = 0;
 
        // Use recursion on all child nodes
        for (Node child : root.children) {
 
            // Get the height of the branch
            int h = postOrder(child, count);
 
            // Initialize height of first
            // explored branch
            if (height == 0)
                height = h;
 
            // If branches are unbalanced
            // then store -1 in height
            else if (h == -1 || height != h)
                height = -1;
        }
 
        // Increment the value of count
        // If height is not -1
        if (height != -1)
            count[0]++;
 
        // Return the height of branches
        // including the root if height is
        // not -1 or else return -1
        return height != -1 ? height + 1 : -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initialize the tree
        Node seven = new Node(7);
        Node seven2 = new Node(7);
        Node five = new Node(5);
        Node four = new Node(4);
        Node nine = new Node(9);
        Node one = new Node(1);
        Node two = new Node(2);
        Node six = new Node(6);
        Node eight = new Node(8);
        Node ten = new Node(10);
        Node three = new Node(3);
        Node mfour = new Node(-4);
        Node mtwo = new Node(-2);
        Node zero = new Node(0);
        three.children.add(mfour);
        three.children.add(mtwo);
        three.children.add(zero);
        ten.children.add(three);
        two.children.add(six);
        two.children.add(seven2);
        four.children.add(nine);
        four.children.add(one);
        four.children.add(five);
        seven.children.add(ten);
        seven.children.add(two);
        seven.children.add(eight);
        seven.children.add(four);
 
        // Call the function
        // and print the result
        System.out.println(
            equalHeightBranches(seven));
    }
 
    static class Node {
 
        List children;
        int val;
 
        // constructor
        public Node(int val)
        {
 
            this.val = val;
            children = new ArrayList<>();
        }
    }
}


Python3
# Python code for the above approach
class Node:
    def __init__(self, val):
        self.val = val
        self.children = []
 
# Post-order traversal to find
# depth of all branches of every
# node of the tree
def postOrder(root, count):
 
        # If root is a leaf node
        # then return 1
    if (len(root.children) == 0):
        return 1
 
    # Initialize a variable height
    # calculate longest increasing path
    height = 0
 
    # Use recursion on all child nodes
    for child in root.children:
 
        # Get the height of the branch
        h = postOrder(child, count)
 
        # Initialize height of first
        # explored branch
        if (height == 0):
            height = h
 
        # If branches are unbalanced
        # then store -1 in height
        elif (h == -1 or height != h):
            height = -1
 
    # Increment the value of count
    #  If height is not -1
    if (height != -1):
        count[0] += 1
 
    # Return the height of branches
    # including the root if height is
    # not -1 or else return -1
    if(height != -1):
        return height + 1
    else:
        return -1
 
# Function to find the number of nodes
# in the N-ary tree with their branches
# having equal height
def equalHeightBranches(root):
 
    # Base case
    if (root == None):
        return 0
 
    # Initialize a variable count
    # to store the answer
    count = [0]
 
    # Apply post order traversal
    # on the tree
    postOrder(root, count)
 
    # Return the answer
    return count[0]
 
# Driver code
 
# Initialize the tree
seven = Node(7)
seven2 = Node(7)
five = Node(5)
four = Node(4)
nine = Node(9)
one = Node(1)
two = Node(2)
six = Node(6)
eight = Node(8)
ten = Node(10)
three = Node(3)
mfour = Node(-4)
mtwo = Node(-2)
zero = Node(0)
three.children.append(mfour)
three.children.append(mtwo)
three.children.append(zero)
ten.children.append(three)
two.children.append(six)
two.children.append(seven2)
four.children.append(nine)
four.children.append(one)
four.children.append(five)
seven.children.append(ten)
seven.children.append(two)
seven.children.append(eight)
seven.children.append(four)
 
# Call the function
# and print the result
print(equalHeightBranches(seven))
 
# This code is contributed by rj13to.


C#
// C# implementation for the above approach
using System;
using System.Collections.Generic;
 
public class Node
{
  public int val;
  public List children;
 
  // Constructor to create a Node
  public Node(int vall)
  {
    val = vall;
    children = new List();
  }
}
 
class GFG {
 
  // Function to find the number of nodes
  // in the N-ary tree with their branches
  // having equal height
  public static int equalHeightBranches(Node root)
  {
 
    // Base case
    if (root == null)
      return 0;
 
    // Initialize a variable count
    // to store the answer
    int[] count = new int[1];
 
    // Apply post order traversal
    // on the tree
    postOrder(root, count);
 
    // Return the answer
    return count[0];
  }
 
  // Post-order traversal to find
  // depth of all branches of every
  // node of the tree
  public static int postOrder(
    Node root, int[] count)
  {
 
    // If root is a leaf node
    // then return 1
    if (root.children.Count == 0)
      return 1;
 
    // Initialize a variable height
    // calculate longest increasing path
    int height = 0;
 
    // Use recursion on all child nodes
    foreach (Node child in root.children) {
 
      // Get the height of the branch
      int h = postOrder(child, count);
 
      // Initialize height of first
      // explored branch
      if (height == 0)
        height = h;
 
      // If branches are unbalanced
      // then store -1 in height
      else if (h == -1 || height != h)
        height = -1;
    }
 
    // Increment the value of count
    // If height is not -1
    if (height != -1)
      count[0]++;
 
    // Return the height of branches
    // including the root if height is
    // not -1 or else return -1
    return height != -1 ? height + 1 : -1;
  }
 
  // Driver code
  public static void Main()
  {
 
    // Initialize the tree
    Node seven = new Node(7);
    Node seven2 = new Node(7);
    Node five = new Node(5);
    Node four = new Node(4);
    Node nine = new Node(9);
    Node one = new Node(1);
    Node two = new Node(2);
    Node six = new Node(6);
    Node eight = new Node(8);
    Node ten = new Node(10);
    Node three = new Node(3);
    Node mfour = new Node(-4);
    Node mtwo = new Node(-2);
    Node zero = new Node(0);
    three.children.Add(mfour);
    three.children.Add(mtwo);
    three.children.Add(zero);
    ten.children.Add(three);
    two.children.Add(six);
    two.children.Add(seven2);
    four.children.Add(nine);
    four.children.Add(one);
    four.children.Add(five);
    seven.children.Add(ten);
    seven.children.Add(two);
    seven.children.Add(eight);
    seven.children.Add(four);
 
    // Call the function
    // and print the result
    Console.WriteLine(
      equalHeightBranches(seven));
  }
}
 
// This code is contributed
// by Shubham Singh


Javascript


输出
4

时间复杂度: O(N)
辅助空间: O(H),其中 H 是树的高度