思路
- 首先得知道层序遍历,反转一般都考虑stack。用一个bool类型标记压左子树还是右子树
import java.util.*;
public class Solution {
public ArrayList<ArrayList<integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<integer>> result=new ArrayList<>();
if(pRoot==null){return result;}
boolean f=false;//fasle表示当前是从左向右
ArrayList<integer> arr=new ArrayList<>();
arr.add(pRoot.val);
Stack<treenode> stack=new Stack<>();
stack.add(pRoot);
while(!stack.isEmpty()){
ArrayList<integer> t=new ArrayList<>();
Stack<treenode> s=new Stack<>();
while(!stack.isEmpty()){
TreeNode p=stack.pop();
t.add(p.val);
if(f){
if(p.right!=null){s.push(p.right);}
if(p.left!=null){s.push(p.left);}
}else{
if(p.left!=null){s.push(p.left);}
if(p.right!=null){s.push(p.right);}
}
}
f=!f;
result.add(t);
stack=s;
}
return result;
}
}
```</treenode></integer></treenode></integer></integer></integer>