简体   繁体   中英

Why do we need multiple constructors for defining a binary tree in Java?

Here is my code for defining a binary tree in Java

// Class definition for binary tree 
// Class for storing a single node of a binary tree of ints
// Cannot be set to be private because this should be accessed by the public class method

public class IntTreeNode {
    public int data;
    public IntTreeNode left;
    public IntTreeNode right;

    // constructs a leaf node with given data
    public IntTreeNode(int data) {
        this(data, null, null);
    }

    // constructs a branch node with given data, left subtree,
    // right subtree
    public IntTreeNode(int data, IntTreeNode left, 
                       IntTreeNode right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
}

Could I ask why we should have two constructors, public IntTreeNode(int data) and public IntTreeNode(int data, IntTreeNode left, IntTreeNode right) ? I ran the code without public IntTreeNode(int data) from a client class, it also works.

They do different things. One makes a new node with no children, one makes a new node with 2 children. While the second will work for both, it provides a more convenient and easier to read api.

Running the code simply with only public IntTreeNode(int data, IntTreeNode left, IntTreeNode right) would be perfectly legal code.

The 2 constructors here are for convenience. For a leaf node, it is not possible to have subtrees. Therefore, the one-parameter constructor provides a convenient way to add a leaf node, with the subtrees defaulted to null . On the other hand, any non-leaf node can have up to 2 subtrees, and so the second constructor exists to create such nodes.

Each constructor has its own role.

First constructor is used when creating a tree which only has a single root node.

Second constructor is used when creating a tree with left and right nodes. Those nodes can be other trees so you can use the second constructor to connect multiple trees.

Technically you are correct, only the second method is needed. But it's a lot clearer when written as two functions, one for leaves, the other for branch nodes. Otherwise the caller has to be told to call IntTreeNode as data,null,null for a leaf.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM