简体   繁体   中英

Complexity of tree traversal for printing all paths recursively

I have written a program to find all valid parameter combination if an input N is given. There should be N number of parameters. For example, if N = 2 , the answer will be ()(), (()) and if N = 3 the answer will be ((())), (())(), ()(()), ()()(), (()()) .

I have implemented the solution using binary tree in Java. Here is my solution.

class Node {
    char value;
    Node right;
    Node left;

    public Node(char value) {
        this.value = value;
    }

    public void insertRight(char value) {
        Node node = new Node(value);
        this.right = node;
    }

    public void insertLeft(char value) {
        Node node = new Node(value);
        this.left = node;
    }
}

public class App
{
    private static final int N = 3;

    public static void main (String[] args)
    {
        Node tree = new Node('(');

        insertNodes(tree, N - 1, 1);

        printParams("", tree);
    }

    private static void insertNodes(Node currentNode, int remainingOpen, int remainingClose) {
        if (remainingOpen > 0) {
            currentNode.insertLeft('(');
            insertNodes(currentNode.left, remainingOpen - 1, remainingClose + 1);
        }
        if (remainingClose > 0) {
            currentNode.insertRight(')');
            insertNodes(currentNode.right, remainingOpen, remainingClose - 1);
        }
    }

    private static void printParams(String paramStr, Node node) {
        paramStr = paramStr + node.value;
        if (node.left == null && node.right == null) {
            System.out.println(paramStr);
            return;
        } 



        if (node.left != null) 
            printParams(paramStr, node.left);

        if (node.right != null)
            printParams(paramStr, node.right);
    }
}

I want to know the complexity of this solution. What would be the complexity for creating the tree and what would be the complexity for traversing on each path?

I know that, there will be 2 * N nodes in each path and there will be at most 2^2N children. If we are traversing each path from root, complexity may be N * 2 ^ 2N . But, I'm not able to think of complexity when recursion is involved.

The complexity for creation is given by the number of nodes you create, which is intuitive enough. Traversal is the same, since you visit each node exactly once.

In your case, the number of nodes form a Catalan sequence: https://en.wikipedia.org/wiki/Catalan_number .

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