【问题标题】:How to get width and height of a binary tree, provided its root node?如何获得二叉树的宽度和高度,提供它的根节点?
【发布时间】:2016-09-09 12:08:40
【问题描述】:

从根节点。 宽度 = 这将是具有更多节点的级别 height = 是根节点的总层数

在下一个示例中,它有 3 个级别(高度=3) 最后一级有3个节点然后widht=3 如何以编程方式获取这些值?

这是我的代码,但总是返回高度 1 和宽度 1

public static void main(String[] args) {
    // TODO code application logic here

    Scanner entradaEscaner = new Scanner (System.in); //Creación de un objeto Scanner

    int valor=0;
    System.out.println("Ingrese el primer valor");
    valor=Integer.valueOf(entradaEscaner.nextLine());

    Nodo nodo = new Nodo(valor);
    Nodo anterior=null;
    boolean continar=true;
    while(continar){

        System.out.println("Nodo actual "+nodo.valor+(anterior!=null?" Nodo anterior "+anterior.valor:""));
        System.out.println("Eliga una opcion");
        System.out.println("1)Ingresar valor izquierda");
        System.out.println("2)Ingresar valor derecha");
        System.out.println("3)Regresar Nodo anteriormente seleccionado ");    
        System.out.println("4)No ingresar mas datos terminar arbol");    


        switch(Integer.valueOf(entradaEscaner.nextLine())){
        case 1:  
            System.out.println("Eligio el Nodo de la izquierda Ingrese un numero");
            anterior=nodo;
            nodo.izquierda= new Nodo(Integer.valueOf(entradaEscaner.nextLine()));
            nodo=nodo.izquierda;
            break;

        case 2:
            System.out.println("Eligio el nodo de la derecha Ingrese un numero");
            anterior=nodo;
            nodo.derecha= new Nodo(Integer.valueOf(entradaEscaner.nextLine()));
            nodo=nodo.derecha;
            break;

        case 3:
            System.out.println("Eligio el nodo anteriormente seleccionado ");
            if(anterior!=null)
            {
                Nodo actual=nodo;
                nodo=anterior;
                anterior=actual;


            }else{
                System.out.println("Pero no existe un nodo anterior, sigues en el nodo actual "+nodo.valor);

            }
            break;

        default:
            continar=false;
            break;

        }

    }


    if(determinarAlturaAnchura(nodo))
        System.out.println("El tamaño de la anchura y altura es el mismo");
    else 
        System.out.println("El tamaño de la anchura y altura NO es el mismo");

}


/*

    /*
    Haciendo uso del proceso del árbol binario y recibiendo como parámetro este proceso, 
    determine si la anchura de dicho árbol es igual a su altura
    */

//recibe un nodo (arbol)
static  boolean determinarAlturaAnchura(Nodo node){


    int tamañoAncho=getMaxWidth(node); 
    int tamañoAlto=height(node);
    System.out.println("El tamaño maximo del ancho es "+tamañoAncho);
    System.out.println("El tamaño maximo del alto es "+tamañoAlto);

    return tamañoAncho==tamañoAlto;



}


/* funcion para conseguir el ancho maximo*/
static int getMaxWidth(Nodo node) 
{
    int maxWidth = 0;
    int width;
    int h = height(node);
    int i;

    /* consigue el tamaño de cada nivel y lo compara con el maximo tamaño */
    for (i = 1; i <= h; i++) 
    {
        width = getWidth(node, i);
        if (width > maxWidth)
            maxWidth = width;
    }

    return maxWidth;
}

/* consigue el tamaño de un nivel */
static  int getWidth(Nodo node, int level) 
{
    if (node == null)
        return 0;

    if (level == 1)
        return 1;
    else if (level > 1)
        return getWidth(node.izquierda, level - 1)
                    + getWidth(node.derecha, level - 1);
    return 0;
}


/* consigue el tamaño de niveles de un arbol*/
static  int height(Nodo node) 
{
    if (node == null)
        return 0;
    else
    {
        /* calcula el tamaño de cada arbol */
        int lHeight = height(node.izquierda);
        int rHeight = height(node.derecha);

        /* usa el mas largo*/
        return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1);
    }
}

【问题讨论】:

  • 理想情况下,如果您需要此信息,您应该在插入树时跟踪它。否则,您将不得不遍历整个树才能弄清楚。
  • 是的,一个要求是有一种方法来获取宽度和高度
  • 在 main 方法中构建树的方式很容易出错。尝试输入序列:1、2、1、3、4。您将得到高度为 2 和宽度为 1,这是正确的。您需要将根节点传递给函数。使用您的代码,您无法返回根节点。保存对第一个节点的引用。如果您需要进一步的帮助,请修改您的代码并编辑您的问题。
  • 即使不懂西班牙语(?)我也可以告诉你,你构建树的方式有问题。该循环允许您 1) 添加节点的第一个子节点 2) 添加节点的第二个子节点或 3) 将创建的最后一个子节点和它添加到的节点交换为添加下一个子节点的目标。这意味着您只能在树中向上遍历一层,这使得在给定的树中同时添加 16 是不可能的,也意味着您不能“返回”到 5 来获取宽度/高度节点。

标签: java tree binary-tree


【解决方案1】:

你的方法getWidth()有很多问题:

  • 您正在为树中的所有不同级别传递root 节点。
  • 您没有跟踪已在该级别遍历的节点数。
  • 在循环下调用getWidth()

如下图进行更改,并将count数组中的最大值值打印为maxWidth:

void getWidth(Nodo node, int level, int count[]) 
{
    if (node != null) 
    {
        count[level]++;
        return getWidth(node.izquierda, count, level + 1)
             + getWidth(node.derecha, count, level + 1);
    }
}

方法height(Nodo node)看起来不错,你的节点插入代码一定有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2015-03-01
    • 2021-09-07
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多