思路:
1.第一行一个头节点,第二行,从右到左输出,第三行,从左到右输出
2.那就是从第一行开始,栈中先存当前节点的左节点,再存右节点,后面从栈中取来,那就是先会找到右节点再左节点,这不就符合第二行节点从右到左吗?然后针对第二行节点,将节点的右左节点先后存入栈,后续取出来,不就是左右输出了么
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>> result = new ArrayList<>();
if (pRoot == null) {
return result;
}
Stack<TreeNode> temp1 = new Stack<>();
Stack<TreeNode> temp2 = new Stack<>();
temp1.push(pRoot);
while (!temp1.isEmpty() || !temp2.isEmpty()) {
ArrayList<Integer> line1 = new ArrayList<>();
ArrayList<Integer> line2 = new ArrayList<>();
while(!temp1.isEmpty()){
TreeNode node = temp1.pop();
line1.add(node.val);
if(node.left != null){
temp2.push(node.left);
}
if(node.right!= null){
temp2.push(node.right);
}
}
while(!temp2.isEmpty()){
TreeNode node = temp2.pop();
line2.add(node.val);
if(node.right != null){
temp1.push(node.right);
}
if(node.left != null){
temp1.push(node.left);
}
}
if (!line1.isEmpty()) {
result.add(line1);
}
if (!line2.isEmpty()) {
result.add(line2);
}
}
return result;
}
}