剑指offer-59-之字形打印二叉树

按之字形顺序打印二叉树

http://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0

思路

  • 首先得知道层序遍历,反转一般都考虑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>

剑指offer与数据结构 文章被收录于专栏

本专栏包括剑指offer题目和一些刷题用的数据结构,单调栈,树状数组,差分数组,后面还会更新红黑树等较为复杂的数据结构

全部评论

相关推荐

想玩飞盘的菠萝蜜在春...:上交✌🏻也拒?
点赞 评论 收藏
分享
哇哇的菜鸡oc:他这不叫校招offer,而是实习offer
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务