Densidad del árbol binario utilizando el recorrido de orden de niveles

Dado un árbol binario, encuentra su densidad haciendo un recorrido.
La densidad del árbol binario se define como: 

Density of Binary Tree = Size / Height 

Ejemplos

Input : 
 Root of following tree
   10
  /   \
 20   30

Output :  1.5
Height of given tree = 2
Size of given tree = 3


Input :
Root of the following tree
     10
    /   
   20   
 /
30
Output : 1
Height of given tree = 3
Size of given tree = 3 

El tamaño y la altura del árbol se pueden encontrar en un solo recorrido utilizando el recorrido de orden de nivel .
Para calcular la altura del árbol binario, la idea es usar un puntero «NULO» como separador entre dos niveles. Cada vez que se produce «NULL» durante el recorrido, se incrementa la altura.
Para calcular el tamaño del árbol binario, incremente el contador para cada nuevo Node encontrado durante el recorrido del orden de niveles.
Finalmente, use la fórmula anterior para calcular la densidad del árbol binario.

A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// A binary tree node
struct Node {
    int data;
    Node *left, *right;
};
 
// Helper function to allocates a new node
Node* newNode(int data)
{
    Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return node;
}
 
// Function to calculate density of Binary Tree
float density(Node* root)
{
    queue<Node*> q;
 
    // push root to queue first
    q.push(root);
     
    // push NULL as a separator
    q.push(NULL);
    int height = 1, size = 0;
    while (!q.empty()) {
        Node* t = q.front();
        q.pop();
        if (t)
            size++;
        else {
 
            // If after popping NULL queue is
            // empty then get out of loop i.e
            // stop the level order traversal.
            if (q.empty())
                break;
            q.push(NULL);
            height++;
            continue;
        }
 
        // if t has left child
        // then push it to queue
        if (t->left) {
            q.push(t->left);
        }
 
        // if t has right child
        // then push it to queue
        if (t->right) {
            q.push(t->right);
        }
    }
    return (float)size / height;
}
 
// Driver code
int main()
{
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
 
    cout << density(root) << endl;
    return 0;
}

Java

// Java implementation of the above approach
import java.util.*;
 
class Solution
{
 
// A binary tree node
static class Node
{
    int data;
    Node left, right;
}
 
// Helper function to allocates a new node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return node;
}
 
// Function to calculate density of Binary Tree
static float density(Node root)
{
    Queue<Node> q = new LinkedList<Node>();
 
    // add root to queue first
    q.add(root);
     
    // add null as a separator
    q.add(null);
    int height = 1, size = 0;
    while (q.size() > 0)
    {
        Node t = q.peek();
        q.remove();
        if (t != null)
            size++;
        else
        {
 
            // If after removeping null queue is
            // empty then get out of loop i.e
            // stop the level order traversal.
            if (q.size() == 0)
                break;
            q.add(null);
            height++;
            continue;
        }
 
        // if t has left child
        // then add it to queue
        if (t.left !=null)
        {
            q.add(t.left);
        }
 
        // if t has right child
        // then add it to queue
        if (t.right != null)
        {
            q.add(t.right);
        }
    }
    return ((float)size )/ height;
}
 
// Driver code
public static void main(String args[])
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
 
    System.out.println(density(root));
}
}
 
// This code is contributed by Arnab Kundu

Python3

# Python implementation of the above approach
 
# Linked List node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Helper function to allocates a new node
def newNode( data) :
 
    node = Node(0)
    node.data = data
    node.left = node.right = None
    return node
 
# Function to calculate density of Binary Tree
def density(root) :
 
    q = []
 
    # append root to queue first
    q.append(root)
     
    # append None as a separator
    q.append(None)
    height = 1
    size = 0
    while (len(q) > 0):
        t = q[0]
        q.pop(0)
        if (t != None):
            size = size + 1
        else:
 
            # If after removeping None queue is
            # empty then get out of loop i.e
            # stop the level order traversal.
            if (len(q) == 0):
                break
            q.append(None)
            height = height + 1
            continue
 
        # if t has left child
        # then append it to queue
        if (t.left != None) :
            q.append(t.left)
 
        # if t has right child
        # then append it to queue
        if (t.right != None):
         
            q.append(t.right)
 
    return (size ) / height
 
# Driver code
 
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
 
print(density(root))
 
# This code is contributed by Arnab Kundu

C#

// C# implementation of the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// A binary tree node
public class Node
{
    public int data;
    public Node left, right;
}
 
// Helper function to allocates a new node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return node;
}
 
// Function to calculate density of Binary Tree
static float density(Node root)
{
    Queue<Node> q = new Queue<Node>();
 
    // add root to queue first
    q.Enqueue(root);
     
    // add null as a separator
    q.Enqueue(null);
    int height = 1, size = 0;
    while (q.Count > 0)
    {
        Node t = q.Peek();
        q.Dequeue();
        if (t != null)
            size++;
        else
        {
 
            // If after removeping null queue is
            // empty then get out of loop i.e
            // stop the level order traversal.
            if (q.Count == 0)
                break;
            q.Enqueue(null);
            height++;
            continue;
        }
 
        // if t has left child
        // then add it to queue
        if (t.left !=null)
        {
            q.Enqueue(t.left);
        }
 
        // if t has right child
        // then add it to queue
        if (t.right != null)
        {
            q.Enqueue(t.right);
        }
    }
    return ((float)size ) / height;
}
 
// Driver code
public static void Main(String []args)
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
 
    Console.WriteLine(density(root));
}
}
 
// This code is contributed by PrinciRaj1992

Javascript

<script>
 
// Javascript implementation of the above approach
 
// A binary tree node
class Node
{
    constructor()
    {
        this.data = 0;
        this.left = null;
        this.right = null;
    }
}
 
// Helper function to allocates a new node
function newNode(data)
{
    var node = new Node();
    node.data = data;
    node.left = node.right = null;
    return node;
}
 
// Function to calculate density of Binary Tree
function density(root)
{
    var q = [];
 
    // Add root to queue first
    q.push(root);
     
    // Add null as a separator
    q.push(null);
    var height = 1, size = 0;
     
    while (q.length > 0)
    {
        var t = q[0];
        q.shift();
         
        if (t != null)
            size++;
        else
        {
             
            // If after removeping null queue is
            // empty then get out of loop i.e
            // stop the level order traversal.
            if (q.length == 0)
                break;
                 
            q.push(null);
            height++;
            continue;
        }
 
        // If t has left child
        // then add it to queue
        if (t.left != null)
        {
            q.push(t.left);
        }
 
        // If t has right child
        // then add it to queue
        if (t.right != null)
        {
            q.push(t.right);
        }
    }
    return(size) / height;
}
 
// Driver code
var root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
 
document.write(density(root));
 
// This code is contributed by noob2000
 
</script>
Producción: 

1.5

 

Complejidad de tiempo : O(N)
 

Publicación traducida automáticamente

Artículo escrito por prajmsidc y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *