我想按级别顺序遍历打印BST。但是我以这种奇怪的方式得到了输出。另外,我使用Java Visualizer来检查算法,但由于Visualizer不能说明多个实例,所以我一无所知。我认为这是我的变量tmp
没有正确添加到ArrayList
实例set
实例中,还是set
没有正确添加到ArrayList<ArrayList<Integer>> solution
中。 / p>
import java.util.LinkedList;
import java.util.Queue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;
public class BSTordertraversal{
public static class TreeNode{
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value){
this.value=value;
}
}
public static ArrayList<ArrayList<Integer>> levelOrder(TreeNode root){
HashMap<TreeNode,Integer> map = new HashMap<>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
ArrayList<Integer> set = new ArrayList<>();
ArrayList<ArrayList<Integer>> solution = new ArrayList<ArrayList<Integer>>();
queue.add(root);
int lastlvl = 0;
map.put(root,0);
if(root==null){
return solution;
}
int tmp;
while(queue.peek()!=null){
TreeNode current = queue.peek();
if(current.left!=null){
queue.add(current.left);
map.put(current.left, map.get(current)+1);
}
if(current.right!=null){
queue.add(current.right);
map.put(current.right, map.get(current)+1);
}
if(map.get(current)==lastlvl){
tmp = current.value;
set.add(tmp);
queue.remove();
}else if(map.get(current)>lastlvl){
solution.add(set);
set.clear();
tmp = current.value;
set.add(tmp);
lastlvl=map.get(current);
queue.remove();
}
}
return solution;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
//root.left.left = new TreeNode(null);
//root.left.right= new TreeNode(null);
root.right.left = new TreeNode(15);
root.right.right= new TreeNode(7);
//root.right.right.right = new TreeNode(30);
ArrayList<ArrayList<Integer>> solution = levelOrder(root);
System.out.println("[");
for(int i=0;i<solution.size();i++){
System.out.print("[");
for(int x=0;x<solution.get(i).size();x++){
System.out.print(solution.get(i).get(x));
}
System.out.print("]");
}
System.out.println("");
System.out.println("]");
}
}
以下是输出:
答案 0 :(得分:0)
我将您的功能levelOrder
稍微更改为:
public static ArrayList<Integer> levelOrder(TreeNode root){
Queue<TreeNode> queue=new LinkedList<TreeNode>();
ArrayList<Integer> levelOrderData = new ArrayList<>();
queue.add(root);
while(!queue.isEmpty())
{
TreeNode tempNode=queue.poll();
levelOrderData.add(tempNode.value);
if(tempNode.left!=null)
queue.add(tempNode.left);
if(tempNode.right!=null)
queue.add(tempNode.right);
}
return levelOrderData;
}
这是不必要的:
ArrayList<ArrayList<Integer>> solution = new ArrayList<ArrayList<Integer>>();