【问题标题】:Getting height of binary tree with objects用对象获取二叉树的高度
【发布时间】:2014-05-01 03:58:55
【问题描述】:

我的教授给了我大部分代码。我们被要求编写并测试一种计算二叉树高度的递归方法。这是我的身高等级

public int height(TreeNode root)
{
    if(root == null)
    {
        return 0; 
    }
    else
    {
        return 1 + Math.max(height(root.lc),
        height(root.rc));
    }
}



public class MainBinaryTreeWithLNRTraversal 
{
    public static void main(String[] arg 
    {
        BinaryTreeWithLNRTraversal t = new BinaryTreeWithLNRTraversal();

        Listing l;
        Listing l1  = new Listing("Ann",    "1st Avenue",  "111 1111");
        Listing l2  = new Listing("Bill",     "2nd Avenue",  "222 2222" );
        Listing l3  = new Listing("Carol",  "3rd Avenue",  "333 3333");
        Listing l4  = new Listing("Mike",   "4th Avenue",  "444 4444");
        Listing l5  = new Listing("Pat",      "5th Avenue",  "555 5555");
        Listing l6  = new Listing("Sally",   "6th Avenue",  "666 6666");
        Listing l7  = new Listing("Ted",     "7th Avenue",  "777 7777");
        Listing l8  = new Listing("Vick",   "8th Avenue",  "888 8888");
        Listing l9  = new Listing("Will",   "9th Avenue",  "999 9999");
        Listing l10 = new Listing("Zack",  "11th Avenue", "101 0101");
        Listing l11 = new Listing("Zeek",  "12th Avenue", "121 2121");
        System.out.println("Tyler Hansen \n");
        // insert the nodes 
        t.insert(l9);
        t.insert(l7);
        t.insert(l10);
        t.insert(l2);
        t.insert(l8);
        t.insert(l1);
        t.insert(l4);
        t.insert(l3);
        t.insert(l6);
        t.insert(l5);
        //Output all the nodes in NLR left tree then right tree order 
        t.showAll();
        t.height();
    }
}

我不知道在高度括号中放入什么。任何帮助或提示将不胜感激,如果需要,我可以提供更多代码。

【问题讨论】:

    标签: java tree binary-tree


    【解决方案1】:

    你需要用t的根节点调用height()

    由于您没有包含BinaryTreeWithLNRTraversal 的定义,我认为这与此有关:https://github.com/DavidSchirduan/ClassProjects/blob/master/CSCI230-java2/Assignment4/BinarySearchTree.java

    由于没有公共访问器来获取树的根节点,因此您的代码将如下所示:

    System.out.println(height(t.root));
    

    如果您的班级和BinaryTreeWithLNRTraversal 在同一个包中,这将起作用。否则,您将需要修改 BinaryTreeWithLNRTraversal 的代码和/或要求您的教授包含一个公共访问器来获取根节点。

    【讨论】:

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