【问题标题】:How to print and display the given input binary tree in java?如何在java中打印和显示给定的输入二叉树?
【发布时间】:2017-02-25 04:05:06
【问题描述】:

如何在java中打印给定的二叉树?以下是我的代码:

JAVA代码:

import java.util.Scanner;

public class binaryexpample1 {

public static void main(String[] args){

         BinaryTree bt = new BinaryTree();
         Scanner input = new Scanner(System.in);

        int x1 = input.nextInt();
        BNode root = bt.addRoot(x1);
        int x2 = input.nextInt();
        BNode y1 = bt.insertLeft(root,x2);
        int x3 = input.nextInt();
        BNode y2 = bt.insertRight(root,x3);
        int x4= input.nextInt();
        BNode y3 = bt.insertLeft(y1,x4);
        int x5 = input.nextInt();
        BNode y4 = bt.insertRight(y1,x3);
        int x6 = input.nextInt();
        BNode y5=bt.insertLeft(y2,x6);
        int x7= input.nextInt();
        BNode y6 = bt.insertRight(y2,x7);
        int x8 = input.nextInt();
        system.out,println()
    }
}

请提出一种实现方法。

【问题讨论】:

  • 嗯,你可以做的第一件事就是把逗号从这里去掉,然后在你的 system.out.println() 中放一个句点。其次,尝试在括号之间添加一些内容。

标签: java data-structures binary-tree


【解决方案1】:

使用中序遍历方法,

public void inOrder(BNode root) {
    if(root == null) {
        return;
    }
    inOrder(root.left);
    System.out.println(root.value);
    inOrder(root.right);
}

在你的主要称呼中,

inOrder(bt.root);

中序遍历的工作原理是通过调用inOrder 沿着节点的左侧向下移动。一旦这些递归调用完成,将打印当前节点的值/数据。然后多次调用inOrder会遍历节点的右侧。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    相关资源
    最近更新 更多