insert(root.right/left, d)
へのあなたの呼び出し、彼らがnullの場合、元の左/右のノードを変更、単にJavaであなたが気づいたように、新しい変数(へメソッドの引数ポイントがありませんが変更されることはありません元の参照)。最初のルートへの変更は、別のメソッドinsert(int)
を呼び出すために機能します。
Node
の代わりに左右BinaryTree
を使用しましたか?また、 "null"を使用する代わりに、 "空の" BinaryTree(NULLルートとisEmpty
メソッド)を持つことを検討してください。
概念的にはです。左と右はノードではなくツリーなので、デザインはよりクリーンになります。
コード例。テストされていないが、アイデアは、右のようになります。
class Node {
BinaryTree left, right;
Integer data;
Node(Integer d, BinaryTree left, BinaryTree right) {
this.data = d;
this.left = left;
this.right = right;
}
}
class BinaryTree {
Node root;
// Empty tree
BinaryTree() {
this(null);
}
BinaryTree(Node root) {
this.root == root;
}
void insert(int d) {
if (this.root == null) {
// The tree was empty, so it creates a new root with empty subtrees
this.root = new Node(d, new BinaryTree(), new BinaryTree());
} else if (d > this.root.data) {
this.root.right.insert(d);
} else if (d < this.root.data) {
this.root.left.insert(d);
}
}
}
注:
- を私はあなたの既存のコードのスタイルを尊重しました。
- この実装は、繰り返し要素をスキップします。
あなたの問題は、あなたがヌル値を "変更"しようとしていることにあります – WuHoUnited
また、最初の挿入メソッドがdを2回挿入しようとしていることに気付いていますか? – WuHoUnited