问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
前序中序后序的遍历不知道哪里错了
```java
import java.io.IOException;
public class dcshu {
public static void main(String[] args) throws IOException{
int i;
int arr[]= {1,2,2,3,4,4,3};
BinaryTree tree=new BinaryTree();
System.out.print("root="+"[");
for(i=0;i<7;i++)
{
System.out.print(arr[i]+" ");
}
System.out.print("]");
System.out.println();
for(i=0;i<arr.length;i++)
{
tree.addto(arr[i]);
}
System.out.println("前序遍历的结果");
tree.PreOrder(tree.rootNode);
System.out.println();
System.out.println("中序遍历的结果");
tree.InOrder(tree.rootNode);
System.out.println();
System.out.println("后序遍历的结果");
tree.PostOrder(tree.rootNode);
}
}
public class dcneed {
int value;
dcneed leftchild;
dcneed rightchild;
public dcneed(int value)
{
this.value=value;
this.leftchild=null;
this.rightchild=null;
}
}
class BinaryTree{
public dcneed rootNode;
public void addto(int value)
{
if(rootNode==null)
{
rootNode=new dcneed(value);
return;
}
dcneed currentNode=rootNode;
while(true)
{
if(value<currentNode.value) {
if(currentNode.leftchild==null) {
currentNode.leftchild=new dcneed(value);
return; }
else currentNode=currentNode.leftchild;
}
else {
if(currentNode.rightchild==null)
{
currentNode.rightchild=new dcneed(value);
return;
}
else
currentNode=currentNode.rightchild;
}
}
}
public void InOrder(dcneed node)
{
if(node!=null) {
InOrder(node.leftchild);
System.out.print(node.value);
InOrder(node.rightchild);
}
}
public void PreOrder(dcneed node)
{
if(node!=null)
{
System.out.print(node.value);
PreOrder(node.leftchild);
PreOrder(node.rightchild);
}
}
public void PostOrder(dcneed node)
{
if(node!=null) {
PostOrder(node.leftchild);
PostOrder(node.rightchild);
System.out.print(node.value);
}
}
}
正确的
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/065729860256177.png "#left")
错误的(我的)
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/659019860256146.png "#left")
```