* Я ответил на свой вопрос ниже *Java- печати дерева рекурсивно с скобкой
Есть другие большие решения, а в этой теме.
* Оригинальный вопрос: *
Я пытался распечатать дерево, которое я построил так:
дерева (корень (20), дерево (корень (15), лист (10), лист (18)), дерево (корень (25), лист (22), лист (27)))
у меня есть следующий код:
static int childlev = 0;//This is global var used to keep track of parentheses
public static void printStruct(MyTree tree, int level) {//This prints out the data structure of the tree
assert tree != null;
if (tree instanceof MyLeaf) {//reached the bottom leaf
MyLeaf leaf = (MyLeaf)tree;
System.out.print(",leaf('" + leaf.value+ "':" + leaf.frequency + ")");
childlev=level;
} else if (tree instanceof MyNode) {//reached a parent
if(childlev>level){//print parentheses when right child leaf is reached and level goes back to parent
for(int i=0;i<childlev-level;i++)//child level minus parent level that we are backing up to
System.out.print(")");
childlev=0;
}
if(level!=0){
System.out.print(",");
}
MyNode node = (MyNode)tree;
System.out.print("tree(root("+node.frequency+")");
// traverse left
printStruct(node.left, level+1);
// traverse right
printStruct(node.right, level+1);
}
}
//at the end of my main after calling above function i have this:
for(int i=0; i<p; i++)//This puts in the final parentheses
System.out.print(")");
в этом выходы:
tree(root(170),tree(root(70),tree(root(32),tree(root(16),tree(root(8),leaf('x':4),tree(root(4),leaf('l':2),leaf('u':2),leaf('h':8),leaf('n':16)),tree(root(38),tree(root(17),leaf('w':8),leaf('o':9)),tree(root(21),tree(root(10),leaf('v':5),leaf('f':5)),tree(root(11),leaf('y':5),tree(root(6),leaf('g':3),leaf('a':3)))))),tree(root(100),tree(root(47),leaf('t':22),tree(root(25),tree(root(12),tree(root(6),leaf('c':3),tree(root(3),leaf('z':1),leaf('d':2),leaf('r':6),leaf('i':13))),tree(root(53),leaf('e':26),leaf('s':27))))
Но, как вы можете видеть, после листа ('u': 2) должно быть 2 круглых скобки, но их нет. Итак, прямо сейчас, если у нас есть правый лист, за которым следует правый лист, мы не печатаем никаких закрывающих круглых скобок. Как это исправить? Спасибо заранее!
'System.out.print (")");' после того, как последний вызов printStruct – Ferrybig
@ Ferrybig Извините, некоторые ошибки, когда я впервые разместил его. Мне действительно нужно было 2 скобки, так что это немного сложнее. – aahmed31
Я думаю, что нашел решение своей проблемы. Я тестирую его прямо сейчас. Я отправлю его как можно скорее. – aahmed31