gpt4 book ai didi

java - 中序遍历给出错误输出

转载 作者:行者123 更新时间:2023-12-04 05:14:18 25 4
gpt4 key购买 nike

class Node {
Node parent;
Node left;
Node right;
int value;

Node (int value) {
this.value = value;
this.parent = null;
this.left = null;
this.right = null;
}
}

class TreeofNodes {
Node insert (Node root, Node node) {
if (root == null)
{
root = node;
return root;
}

Node cur = root;
Node father = root;

while(cur != null)
{
father = cur;
if (cur.value > node.value)
cur = cur.left;
else
cur = cur.right;
}
if(father.value > node.value)
father.left = node;
else
father.right = node;

node.parent = father;

return node;
}

void Inorder (Node n) {
if (n == null)
return;
Inorder (n.left);
System.out.print (n.value + " ");
Inorder (n.right);
}
}

class binarySearchTree {

public static void main (String [] args) {

int A[] = {6, 8, 5, 3, 7, 9, 1};

TreeofNodes obj = new TreeofNodes ( );

Node root = null;
Node n = new Node (A[0]);
root = obj.insert (root, n);

Node Croot = root;

for (int i = 1; i < 7; i++)
{
n = new Node (A[i]);
Croot = obj.insert (Croot, n);
}

System.out.println ("============ Inorder ============");
obj.Inorder (root);
}
}

当我打电话时 Inorder方法,我希望输出是:
 1   3   5   6   7   8   9

但它是
 6   3   7   1   9   5   8

我怀疑我的插入方法是错误的。

有人可以告诉我我错在哪里,我该如何解决?

最佳答案

您的 insert函数返回 node最后而不是 root .改变:

    return node;


    return root;

关于java - 中序遍历给出错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490210/

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