打印从根到节点的所有路径的时间复杂度

时间:2015-02-03 17:04:46

标签: algorithm time-complexity

从根到节点打印所有路径的时间复杂度是多少。 基本上,我正在寻找以下算法的时间复杂性。 遍历树是O(n),其中n是节点数。 但是,除了遍历我也打印。 所以,它的东西就像O(叶子的数量*从根到叶子的路径)。 叶子数空间复杂度最差的情况是O(n)。 路径长度最差的案例空间复杂度也是O(n)。

因此,叶子数= n,从根到叶子的路径长度= n。 因此,是时间复杂度O(n ^ 2)?

public void printPath () {
    doPrint(root, new ArrayList<TreeNode>());
}


private void doPrint(TreeNode node, List<TreeNode> path) {
    if (node == null) return;

    path.add(node);

    if (node.left == null && node.right == null) {
        System.out.println("Path from root: " + root.item + " to leaf: " + node.item + " - ");
        for (TreeNode treeNode : path) {
            System.out.print(treeNode.item + " ");
        }
        System.out.println();
    }

    doPrint(node.left , path);
    doPrint(node.right, path);

    path.remove(path.size() - 1);
}

1 个答案:

答案 0 :(得分:1)

是的,遍历树将是O(n)。如果还在每个叶子上打印路径,则为此添加O(height)因子。就像你说的那样O(n^2)明确地限制了这一点,但是如果你想更准确,你可以把它写成O(n + num_leafs * tree_height)

相关问题