import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(pRoot==null)return res; //这里要求返回thelist而不是null
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(pRoot);
int count = 1;
while(!queue.isEmpty()){
ArrayList<Integer> list = new ArrayList<Integer>();
int size = queue.size();
for(int i=0;i<size;i++){
TreeNode temp = queue.poll();
if(count%2==0){
//从右边到左插入
list.add(0,temp.val);
}else{
list.add(temp.val);
}
if(temp.left!=null){
queue.offer(temp.left);
}
if(temp.right!=null){
queue.offer(temp.right);
}
}
res.add(list);
count++;
}
return res;
}
}
/**
import java.util.*;
public class HelloWorld {
public static void main(String []args) {
System.out.println("Hello World!");
LinkedList<String> list = new LinkedList<String>();
list.add(0,"a");
list.add(0,"b");
list.add(0,"c");
System.out.println("------------------");
list.add("d");
list.add("e");
list.add("f");
for (String str: list) {
System.out.println(str);
}
}
**/
JZ77按之字形顺序打印二叉树
2024-03-18 01:08:06 43 阅读