公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

本文介绍了递归地将项目添加到BST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将项目添加到树中的方法,然后我希望将此树打印到控制台。我有一个继承的类,基于它我需要编写所需的方法:

public abstract class BinaryTreeNode {
    protected int data; // value stored in the node
    protected BinaryTreeNode left, right; // left and right sub-trees

    // constructor
    public BinaryTreeNode(int data) {
        this.data = data;
    }

    // recursively adds an item to the BST
    // @param new data to be stored in the new node
    public abstract void addBSTRecursion(int newNode);

    // prints the tree
    // for example, for a tree:
    //        7
    //    6        8
    // 2     7  4     9
    //
    // write:
    //
    //      2
    //   6
    //      7
    // 7
    //      4
    //   8
    //      9

    // method pseudocode
    //if there is a left subtree then print the left one (recursive call)
    //write out gaps (depending on level), write out data, go to new line
    //if it is right, print the right one (recursive call)
    //@param level the distance of the node from the root. We start from 0.
    public abstract void print(int level);

}

addBSTRecursion(int newNode)-以递归方式将项目添加到BST
print(int level)-如果有左边的子树,则打印左边的子树(递归调用),写出间隙(取决于级别),写出数据,转到新行,如果正确,打印右边的子树(递归调用)
以下是我设法做到的:

public class Node extends BinaryTreeNode {
    public Node(int data) {
        super(data);
    }

    @Override
    public void addBSTRecursion(int newNode) {
        if (data < this.data) {
            if (left != null) {
                left.addBSTRecursion(newNode);
            } else {
                left = new Node(newNode);
            }
        } else {
            if (right != null) {
                right.addBSTRecursion(newNode);
            } else {
                right = new Node(newNode);
            }
        }
    }

    @Override
    public void print(int level) {
        if(this.left != null)this.left.print(level+1);
        for(int n =0; n<level; n++) System.out.print(" ");
        System.out.println(data);
        if(this.right != null)this.right.print(level+1);
    }
}

我的输出:

10
 5
  14

我想收到:

   5
10
   14

推荐答案

这将始终为false,因为它将this.data与自身进行比较:

    if (data < this.data) {

应该是:

    if (newNode < this.data) {

NB:调用参数newNode具有误导性,因为它不是Node类型,而是整数。也可以称之为newData。

这篇关于递归地将项目添加到BST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,

分享到:
标签:BST 添加 递归 项目
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定