[英]How can I modify the traverse of binary search trees?
I successfully made the binary tree but I can't traverse it right. 我成功地制作了二叉树,但我无法正确遍历它。 So this is my binary tree program, and my traverse method.
所以这是我的二叉树程序,以及我的遍历方法。
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);
}
}
I input 我输入
5
3 5 4 2 8
and it returns 然后它回来了
(-,2,-),3,(-,4,-),5,(-,8,-),
rather than 而不是
(-,2,-),3,((-,4,-),5,(-,8,-)),
I tried lots of ways to modify the code to let it do what I want, but all failed... How can I give my program the ability to detect the hierarchy between nodes? 我尝试了很多方法来修改代码,让它做我想做的事,但都失败了......我怎样才能让我的程序能够检测节点之间的层次结构? what modification should I make?
我应该做什么修改? Thx!
谢谢!
You could change to toString
method in Node
: 您可以在
Node
更改为toString
方法:
public String toString() {
String l = Objects.toString(leftChild, "-");
String r = Objects.toString(rightChild, "-");
return "(" + l + "," + key + "," + r + ")";
}
Then you can just call System.out.println(theTree.root)
to see the structure. 然后你可以调用
System.out.println(theTree.root)
来查看结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.