Help with tree recursion

后端 未结 3 2074
醉酒成梦
醉酒成梦 2021-01-15 16:43

I have a Person class, and I want to create a tree. Here is the contsructor for the Person class.

public Person(String name, int age, char gender, Person c1         


        
3条回答
  •  逝去的感伤
    2021-01-15 17:15

    Your code returns 0 if one of the children are null. This is incorrect because you don't account for the other child, or this. The count should always be >= 1 because you always have at least one node in the tree.

    Also, you can't return right away if you see that one child is null. You need to count the other child too (if it exists).

    Here is how I would implement it:

    public int count() // total person count including this object
    {
        int count = 1; // we count this node as 1 
        if (child1 != null) // if we have a left child, count its size
            count += child1.count();
        if (child2 != null) // if we have a right child, count its size
            count += child2.count()
        return count;
    }
    

    You need to account for both children, even if one of them is null.

提交回复
热议问题