微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何打印包含空值的二叉树的级别顺序遍历?爪哇

如何解决如何打印包含空值的二叉树的级别顺序遍历?爪哇

嘿伙计们,我正在尝试打印二叉树的级别顺序遍历,但我无法打印空值(在下面的代码显示为连字符“-”)。你能帮我解决这个问题吗?到目前为止,这是我的代码

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);
    }
}

解决方法

这不是一个有效的解决方案,但它可以完成工作。我只是用 28282828 填充空值并在打印时检查它,这是我的解决方案:

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,writer);

    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。