【问题标题】:Printing BST Formatted Output打印 BST 格式的输出
【发布时间】:2014-07-23 03:47:38
【问题描述】:

我正在尝试打印二叉搜索树并获得以下输出:

-19->4->5->6->259->

如何调整遍历功能,使最后一个箭头不打印在输出中?

我在主函数中使用这段代码:

Tree x = new Tree(5);
x.add(6);
x.add(4);
x.add(259);
x.add(-19);
x.traverse(x);

Tree 类如下:

public class Tree {
    Tree root;
    Tree left;
    Tree right;
    int value; 

public Tree(int value){
    this.value=value;
    this.left=null;
    this.right=null;
}

boolean add(int value){

    if (value == this.value)
        return false;
    else if (value <this.value) {
        if (left == null) {
            left = new Tree(value);
            return true;
        } else
            return left.add(value);
    } else if (value > this.value) {
        if (right == null) {
            right = new Tree(value);
            return true;
        } else
            return right.add(value);
    }
    return false;

}

void traverse(Tree root){

    if (root.left != null){
        traverse(root.left);
    }       

    System.out.printf("%d",root.value);
    System.out.printf("->");
    if (root.right != null){
        traverse(root.right);
    }
}
}

【问题讨论】:

  • 输出现在是-1945->6->259

标签: tree format binary-search-tree tree-traversal


【解决方案1】:

您希望避免只为最后一个(即最大的)元素打印-&gt;。因此,如果节点没有右子节点并且通向它的所有节点都是“正确”节点,则您不想打印它。

void traverse(Tree root, boolean allRight){

    if (root.left != null){
        traverse(root.left, false);
    }       

    System.out.printf("%d",root.value);
    if(!allRight || root.right != null)
        System.out.printf("->");
    if (root.right != null){
        traverse(root.right, allRight);
    }
}

此外,您现在可以这样称呼它:x.traverse(x, true)

【讨论】:

  • 输出现在是-1945->6->259
  • @user40680 希望修复它。
  • 第二次递归调用traverse的第二个参数为true。解决了谢谢!
  • 应该是allRight。已编辑。
【解决方案2】:

这是另一个版本

public boolean traverse(TreeNode root){

    if (root.left != null){
        traverse(root.left);
        System.out.printf("->");

    }       

    System.out.printf("%d",root.value);

    if (root.right != null){
        System.out.printf("->");
        traverse(root.right);           
    }

    return true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多