問題描述
好的,我已經閱讀了所有其他相關問題,但找不到對 java 有幫助的問題.我從解讀其他語言的內容中得到了大致的想法;但我還沒有弄清楚.
Okay, I have read through all the other related questions and cannot find one that helps with java. I get the general idea from deciphering what i can in other languages; but i am yet to figure it out.
問題:我想對排序進行級別排序(我使用遞歸)并以樹的一般形狀將其打印出來.
Problem: I would like to level sort (which i have working using recursion) and print it out in the general shape of a tree.
所以說我有這個:
1
/
2 3
/ /
4 5 6
我的代碼打印出這樣的級別順序:
My code prints out the level order like this:
1 2 3 4 5 6
我想這樣打印出來:
1
2 3
4 5 6
現在,在你給我做一個關于我的工作的道德演講之前......我已經完成了我的 AP Comp Sci 項目,當我的老師提到廣度優先搜索的事情時,我對此感到好奇.
Now before you give me a moral speech about doing my work... I have already finished my AP Comp Sci project and got curious about this when my teacher mentioned the Breadth First Search thing.
我不知道它是否會有所幫助,但這是我目前的代碼:
I don't know if it will help, but here is my code so far:
/**
* Calls the levelOrder helper method and prints out in levelOrder.
*/
public void levelOrder()
{
q = new QueueList();
treeHeight = height();
levelOrder(myRoot, q, myLevel);
}
/**
* Helper method that uses recursion to print out the tree in
* levelOrder
*/
private void levelOrder(TreeNode root, QueueList q, int curLev)
{
System.out.print(curLev);
if(root == null)
{
return;
}
if(q.isEmpty())
{
System.out.println(root.getValue());
}
else
{
System.out.print((String)q.dequeue()+", ");
}
if(root.getLeft() != null)
{
q.enqueue(root.getLeft().getValue());
System.out.println();
}
if(root.getRight() != null)
{
q.enqueue(root.getRight().getValue());
System.out.println();
curLev++;
}
levelOrder(root.getLeft(),q, curLev);
levelOrder(root.getRight(),q, curLev);
}
據我所知,我需要使用樹的總高度,并使用一個級別計數器...唯一的問題是我的級別計數器在我的 levelOrder 使用遞歸返回通過樹時不斷計數.
From what i can figure out, i will need to use the total height of the tree, and use a level counter... Only problem is my level counter keeps counting when my levelOrder uses recursion to go back through the tree.
對不起,如果這太多了,但一些提示會很好.:)
Sorry if this is to much, but some tips would be nice. :)
推薦答案
這是代碼,這個問題是在一次采訪中問我的...
Here is the code, this question was asked to me in one of the interviews...
public void printTree(TreeNode tmpRoot) {
Queue<TreeNode> currentLevel = new LinkedList<TreeNode>();
Queue<TreeNode> nextLevel = new LinkedList<TreeNode>();
currentLevel.add(tmpRoot);
while (!currentLevel.isEmpty()) {
Iterator<TreeNode> iter = currentLevel.iterator();
while (iter.hasNext()) {
TreeNode currentNode = iter.next();
if (currentNode.left != null) {
nextLevel.add(currentNode.left);
}
if (currentNode.right != null) {
nextLevel.add(currentNode.right);
}
System.out.print(currentNode.value + " ");
}
System.out.println();
currentLevel = nextLevel;
nextLevel = new LinkedList<TreeNode>();
}
}
這篇關于Java 使用特定格式的級別順序打印二叉樹的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!