阵列在打印二叉树路径时初始化冗余零

时间:2012-09-29 04:25:48

标签: java arrays data-structures tree binary-tree

我尝试从二叉树中打印所有路径。我能够打印树中的所有路径。但问题是它不能在输出中打印一些冗余零。数组是否用零初始化?如果是,那么如何克服这种情况下的问题呢?我正在学习,这就是为什么我在这里发布这个问题以了解更多并克服错误。

public class PrintAllPath {

static void printAllPaths(Tree tree) {
    int[] paths = new int[1000];
    printPathsRecur(tree, paths, 0);
}

static void printPathsRecur(Tree tree, int paths[], int pathlen) {
    if (tree == null)
        return;
    paths[pathlen++] = tree.val;
    pathlen++;

    if (tree.left == null && tree.right == null) {
        printArray(paths, pathlen);
    } else {
        printPathsRecur(tree.left, paths, pathlen);
        printPathsRecur(tree.right, paths, pathlen);
    }
}

static void printArray(int paths[], int pathlen) {
    for (int i = 0; i < pathlen; i++) {
        System.out.println("Node : " + paths[i]);
    }
}

static Tree insert(Tree tree, int element) {
    Tree tree2 = new Tree(element, null, null);
    if (tree == null)
        tree = tree2;
    else if (element < tree.val)
        tree.left = insert(tree.left, element);
    else
        tree.right = insert(tree.right, element);
    return tree;
}

static void print(Tree tree) {
    if (tree == null)
        return;
    System.out.println(tree.val);
    print(tree.left);
    print(tree.right);
}

public static void main(String[] args) {
    Tree tree = new Tree(new Integer(5), null, null);
    tree = insert(tree, 10);
    tree = insert(tree, 100);
    tree = insert(tree, 11);
    tree = insert(tree, 110);
    tree = insert(tree, 50);
    System.out.println("The tree is as follows : ");
    print(tree);
    printAllPaths(tree);
}
}

输出:

The tree is as follows : 
5
10
100
11
50
110
5 0 10 0 100 0 11 0 50 0 5 0 10 0 100 0 110 0 

3 个答案:

答案 0 :(得分:0)

是的,在Java中,new int[X]创建了一个零初始化数组。

来自JLS §4.12.5

  

每个类变量,实例变量或数组组件在创建时都使用默认值进行初始化(§15.9,§15.10)...对于int类型,默认值为零,即0。

无论如何,你得到零的原因是你每次插入一个元素时都会增加pathlen 两次,所以你插入一个元素然后跳过下一个元素(留下它)在0):

paths[pathlen++] = tree.val;
pathlen++;

你只需要增加一次。

答案 1 :(得分:0)

您正在递增两次pathlen。删除第二个pathlen ++。是的,Java会将所有基元初始化为默认值,包括数组中的默认值。

答案 2 :(得分:0)

你犯的错误是printPathsRecur(Tree tree, int paths[], int pathlen)

paths[pathlen++] = tree.val;
pathlen++;

你将pathlen增加了两个。只从代码中删除pathlen++;才能正常工作。

static void printPathsRecur(Tree tree, int paths[], int pathlen) {
    if (tree == null)
        return;
    paths[pathlen++] = tree.val;
    //pathlen++;

    if (tree.left == null && tree.right == null) {
        printArray(paths, pathlen);
    } else {
        printPathsRecur(tree.left, paths, pathlen);
        printPathsRecur(tree.right, paths, pathlen);
    }
}