【问题标题】:Writing a method that print binary tree and each node level number编写一个打印二叉树和每个节点级别数的方法
【发布时间】:2012-02-05 13:53:37
【问题描述】:

我需要编写一个使用递归打印二叉树的方法。必须是该方法的签名将是

public static void level(Node n)

因此该方法只能获取节点 n 并且不应返回任何内容,只需在屏幕上打印即可。

我的问题是:我需要树上的每个级别都打印有他自己的级别编号, 而且我不知道该怎么做

这是我尝试过的:

public static void level(Node n)
{
    if (n.getLeftSon() == null && n.getRightSon() == null)
        System.out.println(n.getNumber());
    else
    {
        System.out.println(n.getNumber()); 
        if (n.getLeftSon() != null)
            level(n.getLeftSon());
        if (n.getRightSon() != null)
            level(n.getRightSon()); 
    }

}

它可以打印树,但没有每个节点的层数。

好的,所以在论坛的帮助之后,我这样写了这个方法:

public static void level(Node n)
{
    levelAndNumbers(n,0);
}

private static void levelAndNumbers(Node n, int i)
{
    if (n.getLeftSon() == null && n.getRightSon() == null)
        System.out.println(n.getNumber()+"=>"+i);
    else
    {
        System.out.println(n.getNumber()+"=>"+i); 
        if (n.getLeftSon() != null)
            levelAndNumbers(n.getLeftSon(), i+1);
        if (n.getRightSon() != null)
            levelAndNumbers(n.getRightSon(), i+1); 
    }

}

而且效果很好!

所以据我了解,仅在公共方法中没有办法做到这一点?我必须添加另一个获取计数的私有方法...???

【问题讨论】:

    标签: java recursion


    【解决方案1】:

    几乎你已经做了,但有以下修复。

    public static void level(Node n) {
        level(n, 0);
    }
    
    private static void level(Node n, int level) {
       ///..............your logic
       level(n.getLeftSon(), level + 1);
       //...............
       level(n.getRightSon(), level + 1);
    }
    

    顺便说一句,在谈到层次结构时,更有用的名字不是“儿子”而是“孩子”。

    【讨论】:

    • 谢谢你救了我的男人!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 2018-05-14
    相关资源
    最近更新 更多