解题思路1:
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList > Print(TreeNode pRoot) {
//数的层数
int layer = 1;
//存放奇数层的TreeNode
Stack s1 = new Stack();
//存放偶数层的TreeNode
Stack s2 = new Stack();
ArrayList> resultList = new ArrayList>();
//用于存放每一层的结点的值
ArrayList tempList;
s1.push(pRoot);
while(!s1.empty() || !s2.empty()){
tempList = new ArrayList<>();
if(layer%2 != 0){
while(!s1.empty()){
//取出第一个TreeNode
TreeNode node = s1.pop();
if(node != null){
tempList.add(node.val);
//因为下一层是偶数层,是从右向左遍历,而Stack是先进后出,所以先node.left,后node.right
s2.push(node.left);
s2.push(node.right);
}
}
}else{
while(!s2.empty()){
//取出第一个TreeNode
TreeNode node = s2.pop();
if(node != null){
tempList.add(node.val);
//因为下一层是奇数层,是从左向右遍历,而Stack是先进后出,所以先node.right,后node.left
s1.push(node.right);
s1.push(node.left);
}
}
}
if(!tempList.isEmpty()){
resultList.add(tempList);
}
//层数加一
layer++;
}
return resultList;
}
}