我成功制作了二叉树,但我无法正确遍历它。所以这是我的二叉树程序,以及我的遍历方法。
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,-)),
我尝试了很多方法来修改代码让它做我想做的事,但都失败了...... 如何让程序能够检测节点之间的层次结构?我应该做什么修改? THX!
答案 0 :(得分:0)
您可以在toString
中更改为Node
方法:
public String toString() {
String l = Objects.toString(leftChild, "-");
String r = Objects.toString(rightChild, "-");
return "(" + l + "," + key + "," + r + ")";
}
然后,您只需致电System.out.println(theTree.root)
即可查看结构。