gpt4 book ai didi

java - 如何修改二叉搜索树的遍历?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:17:54 25 4
gpt4 key购买 nike

我成功制作了二叉树,但无法正确遍历它。所以这是我的二叉树程序,也是我的遍历方法。

import java.util.*;
public class BinaryTreeUtube {

Node root;
public void addNode(int key) {
Node newNode = new Node(key);

if (root == null) {
root = newNode;

}
else {
Node focusNode = root;
Node parent;
while (true) {
parent = focusNode;
if (key < focusNode.key) {
focusNode = focusNode.leftChild;
if (focusNode == null) {
parent.leftChild = newNode;
return;
}
} else {
focusNode = focusNode.rightChild;
if (focusNode == null) {
parent.rightChild = newNode;
return;
}
}
}
}
}

public void inOrderTraverseTree(Node focusNode) {

if (focusNode != null) {


inOrderTraverseTree(focusNode.leftChild);
System.out.print(focusNode + ",");
inOrderTraverseTree(focusNode.rightChild);

}


}




public Node findNode(int key) {

Node focusNode = root;

while(focusNode.key != key) {
if (key < focusNode.key) {
focusNode = focusNode.leftChild;
}
else {
focusNode = focusNode.rightChild;
}

if (focusNode == null) {
return null;
}
}
return focusNode;
}

public static void main(String[] args){


BinaryTreeUtube theTree = new BinaryTreeUtube();
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
for (int t = 0; t < times; t++) {
theTree.addNode(sc.nextInt());
}




theTree.inOrderTraverseTree(theTree.root);


}

}



class Node {

int key;

Node leftChild;
Node rightChild;

Node(int key) {
this.key = key;
}

public String toString() {
if (leftChild == null) {
return "(-," + Integer.toString(key) + ",-)";
}
return Integer.toString(key);
}
}

我输入

5
3 5 4 2 8

它返回

(-,2,-),3,(-,4,-),5,(-,8,-), 

而不是

(-,2,-),3,((-,4,-),5,(-,8,-)),

我尝试了很多方法来修改代码让它做我想做的事,但都失败了......我怎样才能让我的程序能够检测节点之间的层次结构?我应该做什么修改?谢谢!

最佳答案

您可以在 Node 中更改为 toString 方法:

public String toString() {
String l = Objects.toString(leftChild, "-");
String r = Objects.toString(rightChild, "-");
return "(" + l + "," + key + "," + r + ")";
}

然后你可以调用 System.out.println(theTree.root) 来查看结构。

关于java - 如何修改二叉搜索树的遍历?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com