発生している問題・エラーメッセージ
前提・実現したいこと
バイナリツリーの垂直での出力方法に悩んでいます。
プリントクラスのコードがわかりません。
サンプルの出力は以下です。
Java
1public class Node<T extends Comparable<T>> { 2 T value; 3 Node<T> left, right; 4 5 public void insertToTree(T v) { 6 if (value == null) { 7 value = v; 8 return; 9 } 10 if (v.compareTo(value) < 0) { 11 if (left == null) { 12 left = new Node<T>(); 13 } 14 left.insertToTree(v); 15 } else { 16 if (right == null) { 17 right = new Node<T>(); 18 } 19 right.insertToTree(v); 20 } 21 } 22 23 public void printTree(OutputStreamWriter out) throws IOException { 24 if (right != null) { 25 right.printTree(out, true, ""); 26 } 27 printNodeValue(out); 28 if (left != null) { 29 left.printTree(out, false, ""); 30 } 31 } 32 private void printNodeValue(OutputStreamWriter out) throws IOException { 33 if (value == null) { 34 out.write("<null>"); 35 } else { 36 out.write(value.toString()); 37 } 38 out.write('\n'); 39 } 40 // use string and not stringbuffer on purpose as we need to change the indent at each recursion 41 private void printTree(OutputStreamWriter out, boolean isRight, String indent) throws IOException { 42 if (right != null) { 43 right.printTree(out, true, indent + (isRight ? " " : " | ")); 44 } 45 out.write(indent); 46 if (isRight) { 47 out.write(" /"); 48 } else { 49 out.write(" \"); 50 } 51 out.write("----- "); 52 printNodeValue(out); 53 if (left != null) { 54 left.printTree(out, false, indent + (isRight ? " | " : " ")); 55 } 56 } 57 58}
のコードはエラーが出ていないので合っていると思いますが、出力の際のコードがどうしてもわかりません。
試したこと
試したのは以下のプリントクラスコードです。
java
1 private static Node<Integer> Tree() { 2 Node<Integer> root = new Node<Integer>(99); 3 Node<Integer> n1 = new Node<Integer>(97); 4 Node<Integer> n2 = new Node<Integer>(92); 5 Node<Integer> n3 = new Node<Integer>(83); 6 Node<Integer> n4 = new Node<Integer>(72); 7 ・ 8 ・ 9 ・ 10 11 root.left = n1; 12 root.right = n2; 13 14 n1.left = n2; 15 n1.right = n3; 16 ・ 17 ・ 18 ・
java
1public static void main(String[]args){ 2 binarytree b1=new binarytree(); 3 4 b1.root=new Node(2); 5 6 b1.root.left=new Node(1); 7 b1.root.right=new Node(5); 8 ・ 9 ・ 10 ・
どちらもエラーとなりました。
様々なサイトを見て試してみましたがどうしても理解できません。
ごめんなさい。「プリントクラスのコードがわからない」の意味がわからないです・・・
もう少し適格に状況を質問に補足してもらえないでしょうか
プリントクラスとは?なんですか?
コードがわからない。とは、どういう状態ですか?
> 様々なサイトを見て試してみましたがどうしても理解できません。
・参考にしている?ソースのロジックがわからない
・出力するロジックが書けない?
・出力するロジックは書いた(コンパイルエラーはでない)けど、呼び方がわからない?
> どちらもエラーとなりました。
そもそもエラーになるとは、どういう状態?(例外が発生した?)
値を挿入するコードがわからないという意味です。
下の2つのコードが値を挿入しているクラスのコードです。
この二つだと出力するメソッドが呼び出せず、コンパイルエラーとなってしまいます。
わかりずらく、申し訳ありません。
「サンプルのように表示されるためにツリー構造を作る部分が分からない」ということでしょうか.
そうです。ありがとうございます。
ということは, Node クラスは修正せずにこのまま使うのでしょうか.
今の所エラーがないのでつかえれば良いですが、そもそもNodeクラスのコード自体が間違っているのでしょうか?
それはまだ試しておりませんので分かりませんが, 少なくともサンプルには無い「|」や「/」, 「<null>」等が表示されるかのようになっています.
ツリー構造さえ合っていれば, これらは有っても無くても構わないということでよいのでしょうか.
また, もし Node クラスの表示に不都合があれば, 修正しても良いのでしょうか.
一応構造が理解しやすいかなと思い、そのまま残しているだけなので気にされなくて大丈夫です。
はい。ありがとうございます。
回答2件
あなたの回答
tips
プレビュー