本文介紹了遞歸地將項(xiàng)目添加到BST的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在嘗試創(chuàng)建一個(gè)將項(xiàng)目添加到樹中的方法,然后我希望將此樹打印到控制臺(tái)。我有一個(gè)繼承的類,基于它我需要編寫所需的方法:
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)
-以遞歸方式將項(xiàng)目添加到BST
print(int level)
-如果有左邊的子樹,則打印左邊的子樹(遞歸調(diào)用),寫出間隙(取決于級(jí)別),寫出數(shù)據(jù),轉(zhuǎn)到新行,如果正確,打印右邊的子樹(遞歸調(diào)用)
以下是我設(shè)法做到的:
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
,因?yàn)樗鼘?code>this.data與自身進(jìn)行比較:
if (data < this.data) {
應(yīng)該是:
if (newNode < this.data) {
NB:調(diào)用參數(shù)newNode
具有誤導(dǎo)性,因?yàn)樗皇?code>Node類型,而是整數(shù)。也可以稱之為newData
。
這篇關(guān)于遞歸地將項(xiàng)目添加到BST的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,