简体   繁体   English

如何打印包括 null 值的二叉树的级别顺序遍历? java

[英]how to print level order traversal of binary tree including null values? java

Hey guys i am trying to print the level order traversal of binary tree but i couldnt print the null values(which is shown hypen "-" in my code below).嘿伙计们,我正在尝试打印二叉树的级别顺序遍历,但我无法打印 null 值(在下面的代码中显示为连字符“-”)。 Can you please help me about this?你能帮我解决这个问题吗? Here is my code so far:到目前为止,这是我的代码:

static void printIt(Node root) {
    int h = findHeight(root);
    int i;
    for (i = 1; i <= h; i++)
        writeLevelOrder(root, i);
}


static int findHeight(Node node) {
    if (node == null) {
        return 0;
    }
    return 1 + Math.max(findHeight(node.right), findHeight(node.left));
}

static void writeLevelOrder(Node root, int level) {

    if (root==null) {
        System.out.print("- ");
        return;
    }

    if (level==1){
        System.out.print(root.val + " ");
    }
    else if (level > 1) {
        if (root.left == null) {
            System.out.print("- ");
        }
        if (root.right == null) {
            System.out.print("- ");
        }
        writeLevelOrder(root.left, level - 1);
        writeLevelOrder(root.right, level - 1);
    }
}

it's not a efficient solution but it does the job.I simply fill the null values with 28282828 and check it when it comes to printing, here is my solution:这不是一个有效的解决方案,但它可以完成工作。我只是用 28282828 填充 null 值并在打印时检查它,这是我的解决方案:

static void printIt(Node root, BufferedWriter writer) throws IOException {
    int h = findHeight(root);
    int i;
    for (i = 1; i <= h; i++)
        writeLevelOrder(root, i, writer);
}


static int findHeight(Node node) {

    if (node == null) {
        return 0;
    }
    return 1 + Math.max(findHeight(node.right), findHeight(node.left));
}


static void writeLevelOrder(Node root, int level, BufferedWriter writer) throws IOException {


    if (root == null && level == 1) {
        System.out.print("- ");
        writer.write("- ");
        return;
    }
    if (root == null && level != 1) {
        Node r = new Node(28282828);
        root = r;
        root.left = r;
        root.right = r;
        System.out.print("- ");
        writer.write("- ");
    }
    if (root.val == 28282828 && level != 1) {
        System.out.print("- ");
        writer.write("- ");
    }
    if (level == 1 && root.val != 28282828) {
        System.out.print(root.val + " ");
        writer.write(root.val + " ");
    } else if (level > 1) {
        writeLevelOrder(root.left, level - 1, writer);
        writeLevelOrder(root.right, level - 1, writer);

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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